three.webgpu.js 1013 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562
  1. /**
  2. * @license
  3. * Copyright 2010-2024 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. import { Color, Vector2, Vector3, Vector4, Matrix3, Matrix4, EventDispatcher, MathUtils, ColorManagement, SRGBTransfer, NoToneMapping, StaticDrawUsage, InterleavedBuffer, DynamicDrawUsage, InterleavedBufferAttribute, NoColorSpace, UnsignedIntType, IntType, WebGLCoordinateSystem, BackSide, CubeReflectionMapping, CubeRefractionMapping, WebGPUCoordinateSystem, TangentSpaceNormalMap, ObjectSpaceNormalMap, InstancedInterleavedBuffer, InstancedBufferAttribute, DataArrayTexture, FloatType, FramebufferTexture, LinearMipmapLinearFilter, DepthTexture, Material, NormalBlending, PointsMaterial, LineBasicMaterial, LineDashedMaterial, NoBlending, MeshNormalMaterial, WebGLCubeRenderTarget, BoxGeometry, Mesh, Scene, LinearFilter, CubeCamera, CubeTexture, EquirectangularReflectionMapping, EquirectangularRefractionMapping, AddOperation, MixOperation, MultiplyOperation, MeshBasicMaterial, MeshLambertMaterial, MeshPhongMaterial, Texture, MeshStandardMaterial, MeshPhysicalMaterial, MeshToonMaterial, MeshMatcapMaterial, SpriteMaterial, ShadowMaterial, Uint32BufferAttribute, Uint16BufferAttribute, DoubleSide, DepthStencilFormat, DepthFormat, UnsignedInt248Type, UnsignedByteType, RenderTarget, Plane, Object3D, HalfFloatType, LinearMipMapLinearFilter, OrthographicCamera, BufferGeometry, Float32BufferAttribute, BufferAttribute, UVMapping, Euler, LinearSRGBColorSpace, LessCompare, VSMShadowMap, RGFormat, BasicShadowMap, SphereGeometry, CubeUVReflectionMapping, PerspectiveCamera, RGBAFormat, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, REVISION, SRGBColorSpace, PCFShadowMap, FrontSide, Frustum, DataTexture, RedIntegerFormat, RedFormat, RGIntegerFormat, RGBIntegerFormat, RGBFormat, RGBAIntegerFormat, UnsignedShortType, ByteType, ShortType, createCanvasElement, AddEquation, SubtractEquation, ReverseSubtractEquation, ZeroFactor, OneFactor, SrcColorFactor, SrcAlphaFactor, SrcAlphaSaturateFactor, DstColorFactor, DstAlphaFactor, OneMinusSrcColorFactor, OneMinusSrcAlphaFactor, OneMinusDstColorFactor, OneMinusDstAlphaFactor, CullFaceNone, CullFaceBack, CullFaceFront, CustomBlending, MultiplyBlending, SubtractiveBlending, AdditiveBlending, NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessEqualDepth, LessDepth, AlwaysDepth, NeverDepth, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedInt5999Type, AlphaFormat, LuminanceFormat, LuminanceAlphaFormat, RGB_S3TC_DXT1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_PVRTC_2BPPV1_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGBA_ETC2_EAC_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_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_10x10_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_BPTC_Format, RED_RGTC1_Format, SIGNED_RED_RGTC1_Format, RED_GREEN_RGTC2_Format, SIGNED_RED_GREEN_RGTC2_Format, RepeatWrapping, ClampToEdgeWrapping, MirroredRepeatWrapping, NearestFilter, NearestMipmapNearestFilter, NeverCompare, AlwaysCompare, LessEqualCompare, EqualCompare, GreaterEqualCompare, GreaterCompare, NotEqualCompare, warnOnce, NotEqualStencilFunc, GreaterStencilFunc, GreaterEqualStencilFunc, EqualStencilFunc, LessEqualStencilFunc, LessStencilFunc, AlwaysStencilFunc, NeverStencilFunc, DecrementWrapStencilOp, IncrementWrapStencilOp, DecrementStencilOp, IncrementStencilOp, InvertStencilOp, ReplaceStencilOp, ZeroStencilOp, KeepStencilOp, MaxEquation, MinEquation, SpotLight, PointLight, DirectionalLight, RectAreaLight, AmbientLight, HemisphereLight, LightProbe, LinearToneMapping, ReinhardToneMapping, CineonToneMapping, ACESFilmicToneMapping, AgXToneMapping, NeutralToneMapping, Group, Loader, FileLoader, MaterialLoader, ObjectLoader } from './three.core.js';
  7. export { AdditiveAnimationBlendMode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BasicDepthPacking, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxHelper, BufferGeometryLoader, Cache, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CircleGeometry, Clock, ColorKeyframeTrack, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, Controls, CubeTextureLoader, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceFrontBack, Curve, CurvePath, CustomToneMapping, CylinderGeometry, Cylindrical, Data3DTexture, DataTextureLoader, DataUtils, DefaultLoadingManager, DetachedBindMode, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DynamicCopyUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, ExtrudeGeometry, Fog, FogExp2, GLBufferAttribute, GLSL1, GLSL3, GridHelper, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, InstancedBufferGeometry, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, KeyframeTrack, LOD, LatheGeometry, Layers, Light, Line, Line3, LineCurve, LineCurve3, LineLoop, LineSegments, LinearInterpolant, LinearMipMapNearestFilter, LinearTransfer, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, Matrix2, MeshDepthMaterial, MeshDistanceMaterial, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NormalAnimationBlendMode, NumberKeyframeTrack, OctahedronGeometry, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, PCFSoftShadowMap, Path, PlaneGeometry, PlaneHelper, PointLightHelper, Points, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGDepthPacking, RawShaderMaterial, Ray, Raycaster, RingGeometry, ShaderMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, Spherical, SphericalHarmonics3, SplineCurve, SpotLightHelper, Sprite, StaticCopyUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, TOUCH, TetrahedronGeometry, TextureLoader, TextureUtils, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLRenderTarget, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding } from './three.core.js';
  8. const refreshUniforms = [
  9. 'alphaMap',
  10. 'alphaTest',
  11. 'anisotropy',
  12. 'anisotropyMap',
  13. 'anisotropyRotation',
  14. 'aoMap',
  15. 'attenuationColor',
  16. 'attenuationDistance',
  17. 'bumpMap',
  18. 'clearcoat',
  19. 'clearcoatMap',
  20. 'clearcoatNormalMap',
  21. 'clearcoatNormalScale',
  22. 'clearcoatRoughness',
  23. 'color',
  24. 'dispersion',
  25. 'displacementMap',
  26. 'emissive',
  27. 'emissiveMap',
  28. 'envMap',
  29. 'gradientMap',
  30. 'ior',
  31. 'iridescence',
  32. 'iridescenceIOR',
  33. 'iridescenceMap',
  34. 'iridescenceThicknessMap',
  35. 'lightMap',
  36. 'map',
  37. 'matcap',
  38. 'metalness',
  39. 'metalnessMap',
  40. 'normalMap',
  41. 'normalScale',
  42. 'opacity',
  43. 'roughness',
  44. 'roughnessMap',
  45. 'sheen',
  46. 'sheenColor',
  47. 'sheenColorMap',
  48. 'sheenRoughnessMap',
  49. 'shininess',
  50. 'specular',
  51. 'specularColor',
  52. 'specularColorMap',
  53. 'specularIntensity',
  54. 'specularIntensityMap',
  55. 'specularMap',
  56. 'thickness',
  57. 'transmission',
  58. 'transmissionMap'
  59. ];
  60. class NodeMaterialObserver {
  61. constructor( builder ) {
  62. this.renderObjects = new WeakMap();
  63. this.hasNode = this.containsNode( builder );
  64. this.hasAnimation = builder.object.isSkinnedMesh === true;
  65. this.refreshUniforms = refreshUniforms;
  66. this.renderId = 0;
  67. }
  68. firstInitialization( renderObject ) {
  69. const hasInitialized = this.renderObjects.has( renderObject );
  70. if ( hasInitialized === false ) {
  71. this.getRenderObjectData( renderObject );
  72. return true;
  73. }
  74. return false;
  75. }
  76. getRenderObjectData( renderObject ) {
  77. let data = this.renderObjects.get( renderObject );
  78. if ( data === undefined ) {
  79. const { geometry, material, object } = renderObject;
  80. data = {
  81. material: this.getMaterialData( material ),
  82. geometry: {
  83. attributes: this.getAttributesData( geometry.attributes ),
  84. indexVersion: geometry.index ? geometry.index.version : null,
  85. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  86. },
  87. worldMatrix: object.matrixWorld.clone()
  88. };
  89. if ( object.center ) {
  90. data.center = object.center.clone();
  91. }
  92. if ( object.morphTargetInfluences ) {
  93. data.morphTargetInfluences = object.morphTargetInfluences.slice();
  94. }
  95. if ( renderObject.bundle !== null ) {
  96. data.version = renderObject.bundle.version;
  97. }
  98. if ( data.material.transmission > 0 ) {
  99. const { width, height } = renderObject.context;
  100. data.bufferWidth = width;
  101. data.bufferHeight = height;
  102. }
  103. this.renderObjects.set( renderObject, data );
  104. }
  105. return data;
  106. }
  107. getAttributesData( attributes ) {
  108. const attributesData = {};
  109. for ( const name in attributes ) {
  110. const attribute = attributes[ name ];
  111. attributesData[ name ] = {
  112. version: attribute.version
  113. };
  114. }
  115. return attributesData;
  116. }
  117. containsNode( builder ) {
  118. const material = builder.material;
  119. for ( const property in material ) {
  120. if ( material[ property ] && material[ property ].isNode )
  121. return true;
  122. }
  123. if ( builder.renderer.nodes.modelViewMatrix !== null || builder.renderer.nodes.modelNormalViewMatrix !== null )
  124. return true;
  125. return false;
  126. }
  127. getMaterialData( material ) {
  128. const data = {};
  129. for ( const property of this.refreshUniforms ) {
  130. const value = material[ property ];
  131. if ( value === null || value === undefined ) continue;
  132. if ( typeof value === 'object' && value.clone !== undefined ) {
  133. if ( value.isTexture === true ) {
  134. data[ property ] = { id: value.id, version: value.version };
  135. } else {
  136. data[ property ] = value.clone();
  137. }
  138. } else {
  139. data[ property ] = value;
  140. }
  141. }
  142. return data;
  143. }
  144. equals( renderObject ) {
  145. const { object, material, geometry } = renderObject;
  146. const renderObjectData = this.getRenderObjectData( renderObject );
  147. // world matrix
  148. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  149. renderObjectData.worldMatrix.copy( object.matrixWorld );
  150. return false;
  151. }
  152. // material
  153. const materialData = renderObjectData.material;
  154. for ( const property in materialData ) {
  155. const value = materialData[ property ];
  156. const mtlValue = material[ property ];
  157. if ( value.equals !== undefined ) {
  158. if ( value.equals( mtlValue ) === false ) {
  159. value.copy( mtlValue );
  160. return false;
  161. }
  162. } else if ( mtlValue.isTexture === true ) {
  163. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  164. value.id = mtlValue.id;
  165. value.version = mtlValue.version;
  166. return false;
  167. }
  168. } else if ( value !== mtlValue ) {
  169. materialData[ property ] = mtlValue;
  170. return false;
  171. }
  172. }
  173. if ( materialData.transmission > 0 ) {
  174. const { width, height } = renderObject.context;
  175. if ( renderObjectData.bufferWidth !== width || renderObjectData.bufferHeight !== height ) {
  176. renderObjectData.bufferWidth = width;
  177. renderObjectData.bufferHeight = height;
  178. return false;
  179. }
  180. }
  181. // geometry
  182. const storedGeometryData = renderObjectData.geometry;
  183. const attributes = geometry.attributes;
  184. const storedAttributes = storedGeometryData.attributes;
  185. const storedAttributeNames = Object.keys( storedAttributes );
  186. const currentAttributeNames = Object.keys( attributes );
  187. if ( storedAttributeNames.length !== currentAttributeNames.length ) {
  188. renderObjectData.geometry.attributes = this.getAttributesData( attributes );
  189. return false;
  190. }
  191. // compare each attribute
  192. for ( const name of storedAttributeNames ) {
  193. const storedAttributeData = storedAttributes[ name ];
  194. const attribute = attributes[ name ];
  195. if ( attribute === undefined ) {
  196. // attribute was removed
  197. delete storedAttributes[ name ];
  198. return false;
  199. }
  200. if ( storedAttributeData.version !== attribute.version ) {
  201. storedAttributeData.version = attribute.version;
  202. return false;
  203. }
  204. }
  205. // check index
  206. const index = geometry.index;
  207. const storedIndexVersion = storedGeometryData.indexVersion;
  208. const currentIndexVersion = index ? index.version : null;
  209. if ( storedIndexVersion !== currentIndexVersion ) {
  210. storedGeometryData.indexVersion = currentIndexVersion;
  211. return false;
  212. }
  213. // check drawRange
  214. if ( storedGeometryData.drawRange.start !== geometry.drawRange.start || storedGeometryData.drawRange.count !== geometry.drawRange.count ) {
  215. storedGeometryData.drawRange.start = geometry.drawRange.start;
  216. storedGeometryData.drawRange.count = geometry.drawRange.count;
  217. return false;
  218. }
  219. // morph targets
  220. if ( renderObjectData.morphTargetInfluences ) {
  221. let morphChanged = false;
  222. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  223. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  224. morphChanged = true;
  225. }
  226. }
  227. if ( morphChanged ) return true;
  228. }
  229. // center
  230. if ( renderObjectData.center ) {
  231. if ( renderObjectData.center.equals( object.center ) === false ) {
  232. renderObjectData.center.copy( object.center );
  233. return true;
  234. }
  235. }
  236. // bundle
  237. if ( renderObject.bundle !== null ) {
  238. renderObjectData.version = renderObject.bundle.version;
  239. }
  240. return true;
  241. }
  242. needsRefresh( renderObject, nodeFrame ) {
  243. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) )
  244. return true;
  245. const { renderId } = nodeFrame;
  246. if ( this.renderId !== renderId ) {
  247. this.renderId = renderId;
  248. return true;
  249. }
  250. const isStatic = renderObject.object.static === true;
  251. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  252. if ( isStatic || isBundle )
  253. return false;
  254. const notEqual = this.equals( renderObject ) !== true;
  255. return notEqual;
  256. }
  257. }
  258. /** @module NodeUtils **/
  259. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  260. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  261. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  262. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  263. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  264. function cyrb53( value, seed = 0 ) {
  265. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  266. if ( value instanceof Array ) {
  267. for ( let i = 0, val; i < value.length; i ++ ) {
  268. val = value[ i ];
  269. h1 = Math.imul( h1 ^ val, 2654435761 );
  270. h2 = Math.imul( h2 ^ val, 1597334677 );
  271. }
  272. } else {
  273. for ( let i = 0, ch; i < value.length; i ++ ) {
  274. ch = value.charCodeAt( i );
  275. h1 = Math.imul( h1 ^ ch, 2654435761 );
  276. h2 = Math.imul( h2 ^ ch, 1597334677 );
  277. }
  278. }
  279. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  280. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  281. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  282. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  283. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  284. }
  285. /**
  286. * Computes a hash for the given string.
  287. *
  288. * @method
  289. * @param {String} str - The string to be hashed.
  290. * @return {Number} The hash.
  291. */
  292. const hashString = ( str ) => cyrb53( str );
  293. /**
  294. * Computes a hash for the given array.
  295. *
  296. * @method
  297. * @param {Array<Number>} array - The array to be hashed.
  298. * @return {Number} The hash.
  299. */
  300. const hashArray = ( array ) => cyrb53( array );
  301. /**
  302. * Computes a hash for the given list of parameters.
  303. *
  304. * @method
  305. * @param {...Number} params - A list of parameters.
  306. * @return {Number} The hash.
  307. */
  308. const hash$1 = ( ...params ) => cyrb53( params );
  309. /**
  310. * Computes a cache key for the given node.
  311. *
  312. * @method
  313. * @param {Object} object - The object to be hashed.
  314. * @param {Boolean} [force=false] - Whether to force a cache key computation or not.
  315. * @return {Number} The hash.
  316. */
  317. function getCacheKey$1( object, force = false ) {
  318. const values = [];
  319. if ( object.isNode === true ) {
  320. values.push( object.id );
  321. object = object.getSelf();
  322. }
  323. for ( const { property, childNode } of getNodeChildren( object ) ) {
  324. values.push( values, cyrb53( property.slice( 0, - 4 ) ), childNode.getCacheKey( force ) );
  325. }
  326. return cyrb53( values );
  327. }
  328. /**
  329. * This generator function can be used to iterate over the node children
  330. * of the given object.
  331. *
  332. * @generator
  333. * @param {Object} node - The object to be hashed.
  334. * @param {Boolean} [toJSON=false] - Whether to return JSON or not.
  335. * @yields {Object} A result node holding the property, index (if available) and the child node.
  336. */
  337. function* getNodeChildren( node, toJSON = false ) {
  338. for ( const property in node ) {
  339. // Ignore private properties.
  340. if ( property.startsWith( '_' ) === true ) continue;
  341. const object = node[ property ];
  342. if ( Array.isArray( object ) === true ) {
  343. for ( let i = 0; i < object.length; i ++ ) {
  344. const child = object[ i ];
  345. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  346. yield { property, index: i, childNode: child };
  347. }
  348. }
  349. } else if ( object && object.isNode === true ) {
  350. yield { property, childNode: object };
  351. } else if ( typeof object === 'object' ) {
  352. for ( const subProperty in object ) {
  353. const child = object[ subProperty ];
  354. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  355. yield { property, index: subProperty, childNode: child };
  356. }
  357. }
  358. }
  359. }
  360. }
  361. const typeFromLength = /*@__PURE__*/ new Map( [
  362. [ 1, 'float' ],
  363. [ 2, 'vec2' ],
  364. [ 3, 'vec3' ],
  365. [ 4, 'vec4' ],
  366. [ 9, 'mat3' ],
  367. [ 16, 'mat4' ]
  368. ] );
  369. /**
  370. * Returns the data type for the given the length.
  371. *
  372. * @method
  373. * @param {Number} length - The length.
  374. * @return {String} The data type.
  375. */
  376. function getTypeFromLength( length ) {
  377. return typeFromLength.get( length );
  378. }
  379. /**
  380. * Returns the length for the given data type.
  381. *
  382. * @method
  383. * @param {String} type - The data type.
  384. * @return {Number} The length.
  385. */
  386. function getLengthFromType( type ) {
  387. if ( /float|int|uint/.test( type ) ) return 1;
  388. if ( /vec2/.test( type ) ) return 2;
  389. if ( /vec3/.test( type ) ) return 3;
  390. if ( /vec4/.test( type ) ) return 4;
  391. if ( /mat3/.test( type ) ) return 9;
  392. if ( /mat4/.test( type ) ) return 16;
  393. console.error( 'THREE.TSL: Unsupported type:', type );
  394. }
  395. /**
  396. * Returns the data type for the given value.
  397. *
  398. * @method
  399. * @param {Any} value - The value.
  400. * @return {String?} The data type.
  401. */
  402. function getValueType( value ) {
  403. if ( value === undefined || value === null ) return null;
  404. const typeOf = typeof value;
  405. if ( value.isNode === true ) {
  406. return 'node';
  407. } else if ( typeOf === 'number' ) {
  408. return 'float';
  409. } else if ( typeOf === 'boolean' ) {
  410. return 'bool';
  411. } else if ( typeOf === 'string' ) {
  412. return 'string';
  413. } else if ( typeOf === 'function' ) {
  414. return 'shader';
  415. } else if ( value.isVector2 === true ) {
  416. return 'vec2';
  417. } else if ( value.isVector3 === true ) {
  418. return 'vec3';
  419. } else if ( value.isVector4 === true ) {
  420. return 'vec4';
  421. } else if ( value.isMatrix3 === true ) {
  422. return 'mat3';
  423. } else if ( value.isMatrix4 === true ) {
  424. return 'mat4';
  425. } else if ( value.isColor === true ) {
  426. return 'color';
  427. } else if ( value instanceof ArrayBuffer ) {
  428. return 'ArrayBuffer';
  429. }
  430. return null;
  431. }
  432. /**
  433. * Returns the value/object for the given data type and parameters.
  434. *
  435. * @method
  436. * @param {String} type - The given type.
  437. * @param {...Any} params - A parameter list.
  438. * @return {Any} The value/object.
  439. */
  440. function getValueFromType( type, ...params ) {
  441. const last4 = type ? type.slice( - 4 ) : undefined;
  442. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  443. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  444. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  445. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  446. }
  447. if ( type === 'color' ) {
  448. return new Color( ...params );
  449. } else if ( last4 === 'vec2' ) {
  450. return new Vector2( ...params );
  451. } else if ( last4 === 'vec3' ) {
  452. return new Vector3( ...params );
  453. } else if ( last4 === 'vec4' ) {
  454. return new Vector4( ...params );
  455. } else if ( last4 === 'mat3' ) {
  456. return new Matrix3( ...params );
  457. } else if ( last4 === 'mat4' ) {
  458. return new Matrix4( ...params );
  459. } else if ( type === 'bool' ) {
  460. return params[ 0 ] || false;
  461. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  462. return params[ 0 ] || 0;
  463. } else if ( type === 'string' ) {
  464. return params[ 0 ] || '';
  465. } else if ( type === 'ArrayBuffer' ) {
  466. return base64ToArrayBuffer( params[ 0 ] );
  467. }
  468. return null;
  469. }
  470. /**
  471. * Converts the given array buffer to a Base64 string.
  472. *
  473. * @method
  474. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  475. * @return {String} The Base64 string.
  476. */
  477. function arrayBufferToBase64( arrayBuffer ) {
  478. let chars = '';
  479. const array = new Uint8Array( arrayBuffer );
  480. for ( let i = 0; i < array.length; i ++ ) {
  481. chars += String.fromCharCode( array[ i ] );
  482. }
  483. return btoa( chars );
  484. }
  485. /**
  486. * Converts the given Base64 string to an array buffer.
  487. *
  488. * @method
  489. * @param {String} base64 - The Base64 string.
  490. * @return {ArrayBuffer} The array buffer.
  491. */
  492. function base64ToArrayBuffer( base64 ) {
  493. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  494. }
  495. var NodeUtils = /*#__PURE__*/Object.freeze({
  496. __proto__: null,
  497. arrayBufferToBase64: arrayBufferToBase64,
  498. base64ToArrayBuffer: base64ToArrayBuffer,
  499. getCacheKey: getCacheKey$1,
  500. getLengthFromType: getLengthFromType,
  501. getNodeChildren: getNodeChildren,
  502. getTypeFromLength: getTypeFromLength,
  503. getValueFromType: getValueFromType,
  504. getValueType: getValueType,
  505. hash: hash$1,
  506. hashArray: hashArray,
  507. hashString: hashString
  508. });
  509. /**
  510. * Possible shader stages.
  511. *
  512. * @property {string} VERTEX The vertex shader stage.
  513. * @property {string} FRAGMENT The fragment shader stage.
  514. */
  515. const NodeShaderStage = {
  516. VERTEX: 'vertex',
  517. FRAGMENT: 'fragment'
  518. };
  519. /**
  520. * Update types of a node.
  521. *
  522. * @property {string} NONE The update method is not executed.
  523. * @property {string} FRAME The update method is executed per frame.
  524. * @property {string} RENDER The update method is executed per render. A frame might be produced by multiple render calls so this value allows more detailed updates than FRAME.
  525. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  526. */
  527. const NodeUpdateType = {
  528. NONE: 'none',
  529. FRAME: 'frame',
  530. RENDER: 'render',
  531. OBJECT: 'object'
  532. };
  533. /**
  534. * Data types of a node.
  535. *
  536. * @property {string} BOOLEAN Boolean type.
  537. * @property {string} INTEGER Integer type.
  538. * @property {string} FLOAT Float type.
  539. * @property {string} VECTOR2 Two-dimensional vector type.
  540. * @property {string} VECTOR3 Three-dimensional vector type.
  541. * @property {string} VECTOR4 Four-dimensional vector type.
  542. * @property {string} MATRIX2 2x2 matrix type.
  543. * @property {string} MATRIX3 3x3 matrix type.
  544. * @property {string} MATRIX4 4x4 matrix type.
  545. */
  546. const NodeType = {
  547. BOOLEAN: 'bool',
  548. INTEGER: 'int',
  549. FLOAT: 'float',
  550. VECTOR2: 'vec2',
  551. VECTOR3: 'vec3',
  552. VECTOR4: 'vec4',
  553. MATRIX2: 'mat2',
  554. MATRIX3: 'mat3',
  555. MATRIX4: 'mat4'
  556. };
  557. /**
  558. * Access types of a node. These are relevant for compute and storage usage.
  559. *
  560. * @property {string} READ_ONLY Read-only access
  561. * @property {string} WRITE_ONLY Write-only access.
  562. * @property {string} READ_WRITE Read and write access.
  563. */
  564. const NodeAccess = {
  565. READ_ONLY: 'readOnly',
  566. WRITE_ONLY: 'writeOnly',
  567. READ_WRITE: 'readWrite',
  568. };
  569. const defaultShaderStages = [ 'fragment', 'vertex' ];
  570. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  571. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  572. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  573. let _nodeId = 0;
  574. /**
  575. * Base class for all nodes.
  576. *
  577. * @augments EventDispatcher
  578. */
  579. class Node extends EventDispatcher {
  580. static get type() {
  581. return 'Node';
  582. }
  583. /**
  584. * Constructs a new node.
  585. *
  586. * @param {String?} nodeType - The node type.
  587. */
  588. constructor( nodeType = null ) {
  589. super();
  590. /**
  591. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  592. *
  593. * @type {String?}
  594. * @default null
  595. */
  596. this.nodeType = nodeType;
  597. /**
  598. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  599. *
  600. * @type {String}
  601. * @default 'none'
  602. */
  603. this.updateType = NodeUpdateType.NONE;
  604. /**
  605. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  606. *
  607. * @type {String}
  608. * @default 'none'
  609. */
  610. this.updateBeforeType = NodeUpdateType.NONE;
  611. /**
  612. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  613. *
  614. * @type {String}
  615. * @default 'none'
  616. */
  617. this.updateAfterType = NodeUpdateType.NONE;
  618. /**
  619. * The UUID of the node.
  620. *
  621. * @type {String}
  622. * @readonly
  623. */
  624. this.uuid = MathUtils.generateUUID();
  625. /**
  626. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  627. *
  628. * @type {Number}
  629. * @readonly
  630. * @default 0
  631. */
  632. this.version = 0;
  633. /**
  634. * Whether this node is global or not. This property is relevant for the internal
  635. * node caching system. All nodes which should be declared just once should
  636. * set this flag to `true` (a typical example is {@link AttributeNode}).
  637. *
  638. * @type {Boolean}
  639. * @default false
  640. */
  641. this.global = false;
  642. /**
  643. * This flag can be used for type testing.
  644. *
  645. * @type {Boolean}
  646. * @readonly
  647. * @default true
  648. */
  649. this.isNode = true;
  650. // private
  651. /**
  652. * The cache key of this node.
  653. *
  654. * @private
  655. * @type {Number?}
  656. * @default null
  657. */
  658. this._cacheKey = null;
  659. /**
  660. * The cache key 's version.
  661. *
  662. * @private
  663. * @type {Number}
  664. * @default 0
  665. */
  666. this._cacheKeyVersion = 0;
  667. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  668. }
  669. /**
  670. * Set this property to `true` when the node should be regenerated.
  671. *
  672. * @type {Boolean}
  673. * @default false
  674. */
  675. set needsUpdate( value ) {
  676. if ( value === true ) {
  677. this.version ++;
  678. }
  679. }
  680. /**
  681. * The type of the class. The value is usually the constructor name.
  682. *
  683. * @type {String}
  684. * @readonly
  685. */
  686. get type() {
  687. return this.constructor.type;
  688. }
  689. /**
  690. * Convenient method for defining {@link Node#update}.
  691. *
  692. * @param {Function} callback - The update method.
  693. * @param {String} updateType - The update type.
  694. * @return {Node} A reference to this node.
  695. */
  696. onUpdate( callback, updateType ) {
  697. this.updateType = updateType;
  698. this.update = callback.bind( this.getSelf() );
  699. return this;
  700. }
  701. /**
  702. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  703. * this method automatically sets the update type to `FRAME`.
  704. *
  705. * @param {Function} callback - The update method.
  706. * @return {Node} A reference to this node.
  707. */
  708. onFrameUpdate( callback ) {
  709. return this.onUpdate( callback, NodeUpdateType.FRAME );
  710. }
  711. /**
  712. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  713. * this method automatically sets the update type to `RENDER`.
  714. *
  715. * @param {Function} callback - The update method.
  716. * @return {Node} A reference to this node.
  717. */
  718. onRenderUpdate( callback ) {
  719. return this.onUpdate( callback, NodeUpdateType.RENDER );
  720. }
  721. /**
  722. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  723. * this method automatically sets the update type to `OBJECT`.
  724. *
  725. * @param {Function} callback - The update method.
  726. * @return {Node} A reference to this node.
  727. */
  728. onObjectUpdate( callback ) {
  729. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  730. }
  731. /**
  732. * Convenient method for defining {@link Node#updateReference}.
  733. *
  734. * @param {Function} callback - The update method.
  735. * @return {Node} A reference to this node.
  736. */
  737. onReference( callback ) {
  738. this.updateReference = callback.bind( this.getSelf() );
  739. return this;
  740. }
  741. /**
  742. * The `this` reference might point to a Proxy so this method can be used
  743. * to get the reference to the actual node instance.
  744. *
  745. * @return {Node} A reference to the node.
  746. */
  747. getSelf() {
  748. // Returns non-node object.
  749. return this.self || this;
  750. }
  751. /**
  752. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  753. * to such objects based on a given state (e.g. the current node frame or builder).
  754. *
  755. * @param {Any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  756. * @return {Any} The updated reference.
  757. */
  758. updateReference( /*state*/ ) {
  759. return this;
  760. }
  761. /**
  762. * By default this method returns the value of the {@link Node#global} flag. This method
  763. * can be overwritten in derived classes if an analytical way is required to determine the
  764. * global status.
  765. *
  766. * @param {NodeBuilder} builder - The current node builder.
  767. * @return {Boolean} Whether this node is global or not.
  768. */
  769. isGlobal( /*builder*/ ) {
  770. return this.global;
  771. }
  772. /**
  773. * Generator function that can be used to iterate over the child nodes.
  774. *
  775. * @generator
  776. * @yields {Node} A child node.
  777. */
  778. * getChildren() {
  779. for ( const { childNode } of getNodeChildren( this ) ) {
  780. yield childNode;
  781. }
  782. }
  783. /**
  784. * Calling this method dispatches the `dispose` event. This event can be used
  785. * to register event listeners for clean up tasks.
  786. */
  787. dispose() {
  788. this.dispatchEvent( { type: 'dispose' } );
  789. }
  790. /**
  791. * Callback for {@link Node#traverse}.
  792. *
  793. * @callback traverseCallback
  794. * @param {Node} node - The current node.
  795. */
  796. /**
  797. * Can be used to traverse through the node's hierarchy.
  798. *
  799. * @param {traverseCallback} callback - A callback that is executed per node.
  800. */
  801. traverse( callback ) {
  802. callback( this );
  803. for ( const childNode of this.getChildren() ) {
  804. childNode.traverse( callback );
  805. }
  806. }
  807. /**
  808. * Returns the cache key for this node.
  809. *
  810. * @param {Boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  811. * @return {Number} The cache key of the node.
  812. */
  813. getCacheKey( force = false ) {
  814. force = force || this.version !== this._cacheKeyVersion;
  815. if ( force === true || this._cacheKey === null ) {
  816. this._cacheKey = getCacheKey$1( this, force );
  817. this._cacheKeyVersion = this.version;
  818. }
  819. return this._cacheKey;
  820. }
  821. /**
  822. * Returns the references to this node which is by default `this`.
  823. *
  824. * @return {Node} A reference to this node.
  825. */
  826. getScope() {
  827. return this;
  828. }
  829. /**
  830. * Returns the hash of the node which is used to identify the node. By default it's
  831. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  832. * depending on their implementation.
  833. *
  834. * @param {NodeBuilder} builder - The current node builder.
  835. * @return {String} The hash.
  836. */
  837. getHash( /*builder*/ ) {
  838. return this.uuid;
  839. }
  840. /**
  841. * Returns the update type of {@link Node#update}.
  842. *
  843. * @return {NodeUpdateType} The update type.
  844. */
  845. getUpdateType() {
  846. return this.updateType;
  847. }
  848. /**
  849. * Returns the update type of {@link Node#updateBefore}.
  850. *
  851. * @return {NodeUpdateType} The update type.
  852. */
  853. getUpdateBeforeType() {
  854. return this.updateBeforeType;
  855. }
  856. /**
  857. * Returns the update type of {@link Node#updateAfter}.
  858. *
  859. * @return {NodeUpdateType} The update type.
  860. */
  861. getUpdateAfterType() {
  862. return this.updateAfterType;
  863. }
  864. /**
  865. * Certain types are composed of multiple elements. For example a `vec3`
  866. * is composed of three `float` values. This method returns the type of
  867. * these elements.
  868. *
  869. * @param {NodeBuilder} builder - The current node builder.
  870. * @return {String} The type of the node.
  871. */
  872. getElementType( builder ) {
  873. const type = this.getNodeType( builder );
  874. const elementType = builder.getElementType( type );
  875. return elementType;
  876. }
  877. /**
  878. * Returns the node's type.
  879. *
  880. * @param {NodeBuilder} builder - The current node builder.
  881. * @return {String} The type of the node.
  882. */
  883. getNodeType( builder ) {
  884. const nodeProperties = builder.getNodeProperties( this );
  885. if ( nodeProperties.outputNode ) {
  886. return nodeProperties.outputNode.getNodeType( builder );
  887. }
  888. return this.nodeType;
  889. }
  890. /**
  891. * This method is used during the build process of a node and ensures
  892. * equal nodes are not built multiple times but just once. For example if
  893. * `attribute( 'uv' )` is used multiple times by the user, the build
  894. * process makes sure to process just the first node.
  895. *
  896. * @param {NodeBuilder} builder - The current node builder.
  897. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  898. */
  899. getShared( builder ) {
  900. const hash = this.getHash( builder );
  901. const nodeFromHash = builder.getNodeFromHash( hash );
  902. return nodeFromHash || this;
  903. }
  904. /**
  905. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  906. * This method is often overwritten in derived modules to prepare the node which is used as the output/result.
  907. * The output node must be returned in the `return` statement.
  908. *
  909. * @param {NodeBuilder} builder - The current node builder.
  910. * @return {Node?} The output node.
  911. */
  912. setup( builder ) {
  913. const nodeProperties = builder.getNodeProperties( this );
  914. let index = 0;
  915. for ( const childNode of this.getChildren() ) {
  916. nodeProperties[ 'node' + index ++ ] = childNode;
  917. }
  918. // return a outputNode if exists
  919. return null;
  920. }
  921. /**
  922. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  923. * This stage anaylzes the node hierarchy and ensures descendent nodes are built.
  924. *
  925. * @param {NodeBuilder} builder - The current node builder.
  926. */
  927. analyze( builder ) {
  928. const usageCount = builder.increaseUsage( this );
  929. if ( usageCount === 1 ) {
  930. // node flow children
  931. const nodeProperties = builder.getNodeProperties( this );
  932. for ( const childNode of Object.values( nodeProperties ) ) {
  933. if ( childNode && childNode.isNode === true ) {
  934. childNode.build( builder );
  935. }
  936. }
  937. }
  938. }
  939. /**
  940. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  941. * This state builds the output node and returns the resulting shader string.
  942. *
  943. * @param {NodeBuilder} builder - The current node builder.
  944. * @param {String?} output - Can be used to define the output type.
  945. * @return {String?} The generated shader string.
  946. */
  947. generate( builder, output ) {
  948. const { outputNode } = builder.getNodeProperties( this );
  949. if ( outputNode && outputNode.isNode === true ) {
  950. return outputNode.build( builder, output );
  951. }
  952. }
  953. /**
  954. * The method can be implemented to update the node's internal state before it is used to render an object.
  955. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  956. *
  957. * @param {NodeFrame} frame - A reference to the current node frame.
  958. */
  959. updateBefore( /*frame*/ ) {
  960. console.warn( 'Abstract function.' );
  961. }
  962. /**
  963. * The method can be implemented to update the node's internal state after it was used to render an object.
  964. * The {@link Node#updateAfterType} property defines how often the update is executed.
  965. *
  966. * @param {NodeFrame} frame - A reference to the current node frame.
  967. */
  968. updateAfter( /*frame*/ ) {
  969. console.warn( 'Abstract function.' );
  970. }
  971. /**
  972. * The method can be implemented to update the node's internal state when it is used to render an object.
  973. * The {@link Node#updateType} property defines how often the update is executed.
  974. *
  975. * @param {NodeFrame} frame - A reference to the current node frame.
  976. */
  977. update( /*frame*/ ) {
  978. console.warn( 'Abstract function.' );
  979. }
  980. /**
  981. * This method performs the build of a node. The behavior of this method as well as its return value depend
  982. * on the current build stage (setup, analyze or generate).
  983. *
  984. * @param {NodeBuilder} builder - The current node builder.
  985. * @param {String?} output - Can be used to define the output type.
  986. * @return {String?} When this method is executed in the setup or analyze stage, `null` is returned. In the generate stage, the generated shader string.
  987. */
  988. build( builder, output = null ) {
  989. const refNode = this.getShared( builder );
  990. if ( this !== refNode ) {
  991. return refNode.build( builder, output );
  992. }
  993. builder.addNode( this );
  994. builder.addChain( this );
  995. /* Build stages expected results:
  996. - "setup" -> Node
  997. - "analyze" -> null
  998. - "generate" -> String
  999. */
  1000. let result = null;
  1001. const buildStage = builder.getBuildStage();
  1002. if ( buildStage === 'setup' ) {
  1003. this.updateReference( builder );
  1004. const properties = builder.getNodeProperties( this );
  1005. if ( properties.initialized !== true ) {
  1006. const stackNodesBeforeSetup = builder.stack.nodes.length;
  1007. properties.initialized = true;
  1008. properties.outputNode = this.setup( builder );
  1009. if ( properties.outputNode !== null && builder.stack.nodes.length !== stackNodesBeforeSetup ) ;
  1010. for ( const childNode of Object.values( properties ) ) {
  1011. if ( childNode && childNode.isNode === true ) {
  1012. childNode.build( builder );
  1013. }
  1014. }
  1015. }
  1016. } else if ( buildStage === 'analyze' ) {
  1017. this.analyze( builder );
  1018. } else if ( buildStage === 'generate' ) {
  1019. const isGenerateOnce = this.generate.length === 1;
  1020. if ( isGenerateOnce ) {
  1021. const type = this.getNodeType( builder );
  1022. const nodeData = builder.getDataFromNode( this );
  1023. result = nodeData.snippet;
  1024. if ( result === undefined ) {
  1025. result = this.generate( builder ) || '';
  1026. nodeData.snippet = result;
  1027. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1028. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1029. }
  1030. result = builder.format( result, type, output );
  1031. } else {
  1032. result = this.generate( builder, output ) || '';
  1033. }
  1034. }
  1035. builder.removeChain( this );
  1036. builder.addSequentialNode( this );
  1037. return result;
  1038. }
  1039. /**
  1040. * Returns the child nodes as a JSON object.
  1041. *
  1042. * @return {Object} The serialized child objects as JSON.
  1043. */
  1044. getSerializeChildren() {
  1045. return getNodeChildren( this );
  1046. }
  1047. /**
  1048. * Serializes the node to JSON.
  1049. *
  1050. * @param {Object} json - The output JSON object.
  1051. */
  1052. serialize( json ) {
  1053. const nodeChildren = this.getSerializeChildren();
  1054. const inputNodes = {};
  1055. for ( const { property, index, childNode } of nodeChildren ) {
  1056. if ( index !== undefined ) {
  1057. if ( inputNodes[ property ] === undefined ) {
  1058. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1059. }
  1060. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1061. } else {
  1062. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1063. }
  1064. }
  1065. if ( Object.keys( inputNodes ).length > 0 ) {
  1066. json.inputNodes = inputNodes;
  1067. }
  1068. }
  1069. /**
  1070. * Deserializes the node from the given JSON.
  1071. *
  1072. * @param {Object} json - The JSON object.
  1073. */
  1074. deserialize( json ) {
  1075. if ( json.inputNodes !== undefined ) {
  1076. const nodes = json.meta.nodes;
  1077. for ( const property in json.inputNodes ) {
  1078. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1079. const inputArray = [];
  1080. for ( const uuid of json.inputNodes[ property ] ) {
  1081. inputArray.push( nodes[ uuid ] );
  1082. }
  1083. this[ property ] = inputArray;
  1084. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1085. const inputObject = {};
  1086. for ( const subProperty in json.inputNodes[ property ] ) {
  1087. const uuid = json.inputNodes[ property ][ subProperty ];
  1088. inputObject[ subProperty ] = nodes[ uuid ];
  1089. }
  1090. this[ property ] = inputObject;
  1091. } else {
  1092. const uuid = json.inputNodes[ property ];
  1093. this[ property ] = nodes[ uuid ];
  1094. }
  1095. }
  1096. }
  1097. }
  1098. /**
  1099. * Serializes the node into the three.js JSON Object/Scene format.
  1100. *
  1101. * @param {Object?} meta - An optional JSON object that already holds serialized data from other scene objects.
  1102. * @return {Object} The serialized node.
  1103. */
  1104. toJSON( meta ) {
  1105. const { uuid, type } = this;
  1106. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1107. if ( isRoot ) {
  1108. meta = {
  1109. textures: {},
  1110. images: {},
  1111. nodes: {}
  1112. };
  1113. }
  1114. // serialize
  1115. let data = meta.nodes[ uuid ];
  1116. if ( data === undefined ) {
  1117. data = {
  1118. uuid,
  1119. type,
  1120. meta,
  1121. metadata: {
  1122. version: 4.6,
  1123. type: 'Node',
  1124. generator: 'Node.toJSON'
  1125. }
  1126. };
  1127. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1128. this.serialize( data );
  1129. delete data.meta;
  1130. }
  1131. // TODO: Copied from Object3D.toJSON
  1132. function extractFromCache( cache ) {
  1133. const values = [];
  1134. for ( const key in cache ) {
  1135. const data = cache[ key ];
  1136. delete data.metadata;
  1137. values.push( data );
  1138. }
  1139. return values;
  1140. }
  1141. if ( isRoot ) {
  1142. const textures = extractFromCache( meta.textures );
  1143. const images = extractFromCache( meta.images );
  1144. const nodes = extractFromCache( meta.nodes );
  1145. if ( textures.length > 0 ) data.textures = textures;
  1146. if ( images.length > 0 ) data.images = images;
  1147. if ( nodes.length > 0 ) data.nodes = nodes;
  1148. }
  1149. return data;
  1150. }
  1151. }
  1152. class ArrayElementNode extends Node {
  1153. static get type() {
  1154. return 'ArrayElementNode';
  1155. } // @TODO: If extending from TempNode it breaks webgpu_compute
  1156. constructor( node, indexNode ) {
  1157. super();
  1158. this.node = node;
  1159. this.indexNode = indexNode;
  1160. this.isArrayElementNode = true;
  1161. }
  1162. getNodeType( builder ) {
  1163. return this.node.getElementType( builder );
  1164. }
  1165. generate( builder ) {
  1166. const nodeSnippet = this.node.build( builder );
  1167. const indexSnippet = this.indexNode.build( builder, 'uint' );
  1168. return `${nodeSnippet}[ ${indexSnippet} ]`;
  1169. }
  1170. }
  1171. class ConvertNode extends Node {
  1172. static get type() {
  1173. return 'ConvertNode';
  1174. }
  1175. constructor( node, convertTo ) {
  1176. super();
  1177. this.node = node;
  1178. this.convertTo = convertTo;
  1179. }
  1180. getNodeType( builder ) {
  1181. const requestType = this.node.getNodeType( builder );
  1182. let convertTo = null;
  1183. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1184. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1185. convertTo = overloadingType;
  1186. }
  1187. }
  1188. return convertTo;
  1189. }
  1190. serialize( data ) {
  1191. super.serialize( data );
  1192. data.convertTo = this.convertTo;
  1193. }
  1194. deserialize( data ) {
  1195. super.deserialize( data );
  1196. this.convertTo = data.convertTo;
  1197. }
  1198. generate( builder, output ) {
  1199. const node = this.node;
  1200. const type = this.getNodeType( builder );
  1201. const snippet = node.build( builder, type );
  1202. return builder.format( snippet, type, output );
  1203. }
  1204. }
  1205. /**
  1206. * This module uses cache management to create temporary variables
  1207. * if the node is used more than once to prevent duplicate calculations.
  1208. *
  1209. * The class acts as a base class for many other nodes types.
  1210. *
  1211. * @augments Node
  1212. */
  1213. class TempNode extends Node {
  1214. static get type() {
  1215. return 'TempNode';
  1216. }
  1217. /**
  1218. * Constructs a temp node.
  1219. *
  1220. * @param {String} nodeType - The node type.
  1221. */
  1222. constructor( type ) {
  1223. super( type );
  1224. /**
  1225. * This flag can be used for type testing.
  1226. *
  1227. * @type {Boolean}
  1228. * @readonly
  1229. * @default true
  1230. */
  1231. this.isTempNode = true;
  1232. }
  1233. /**
  1234. * Whether this node is used more than once in context of other nodes.
  1235. *
  1236. * @return {Boolean} A flag that indicates if there is more than one dependency to other nodes.
  1237. */
  1238. hasDependencies( builder ) {
  1239. return builder.getDataFromNode( this ).usageCount > 1;
  1240. }
  1241. build( builder, output ) {
  1242. const buildStage = builder.getBuildStage();
  1243. if ( buildStage === 'generate' ) {
  1244. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1245. const nodeData = builder.getDataFromNode( this );
  1246. if ( nodeData.propertyName !== undefined ) {
  1247. return builder.format( nodeData.propertyName, type, output );
  1248. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1249. const snippet = super.build( builder, type );
  1250. const nodeVar = builder.getVarFromNode( this, null, type );
  1251. const propertyName = builder.getPropertyName( nodeVar );
  1252. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  1253. nodeData.snippet = snippet;
  1254. nodeData.propertyName = propertyName;
  1255. return builder.format( nodeData.propertyName, type, output );
  1256. }
  1257. }
  1258. return super.build( builder, output );
  1259. }
  1260. }
  1261. class JoinNode extends TempNode {
  1262. static get type() {
  1263. return 'JoinNode';
  1264. }
  1265. constructor( nodes = [], nodeType = null ) {
  1266. super( nodeType );
  1267. this.nodes = nodes;
  1268. }
  1269. getNodeType( builder ) {
  1270. if ( this.nodeType !== null ) {
  1271. return builder.getVectorType( this.nodeType );
  1272. }
  1273. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1274. }
  1275. generate( builder, output ) {
  1276. const type = this.getNodeType( builder );
  1277. const nodes = this.nodes;
  1278. const primitiveType = builder.getComponentType( type );
  1279. const snippetValues = [];
  1280. for ( const input of nodes ) {
  1281. let inputSnippet = input.build( builder );
  1282. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  1283. if ( inputPrimitiveType !== primitiveType ) {
  1284. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  1285. }
  1286. snippetValues.push( inputSnippet );
  1287. }
  1288. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1289. return builder.format( snippet, type, output );
  1290. }
  1291. }
  1292. const stringVectorComponents = vectorComponents.join( '' );
  1293. class SplitNode extends Node {
  1294. static get type() {
  1295. return 'SplitNode';
  1296. }
  1297. constructor( node, components = 'x' ) {
  1298. super();
  1299. this.node = node;
  1300. this.components = components;
  1301. this.isSplitNode = true;
  1302. }
  1303. getVectorLength() {
  1304. let vectorLength = this.components.length;
  1305. for ( const c of this.components ) {
  1306. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1307. }
  1308. return vectorLength;
  1309. }
  1310. getComponentType( builder ) {
  1311. return builder.getComponentType( this.node.getNodeType( builder ) );
  1312. }
  1313. getNodeType( builder ) {
  1314. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1315. }
  1316. generate( builder, output ) {
  1317. const node = this.node;
  1318. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1319. let snippet = null;
  1320. if ( nodeTypeLength > 1 ) {
  1321. let type = null;
  1322. const componentsLength = this.getVectorLength();
  1323. if ( componentsLength >= nodeTypeLength ) {
  1324. // needed expand the input node
  1325. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1326. }
  1327. const nodeSnippet = node.build( builder, type );
  1328. if ( this.components.length === nodeTypeLength && this.components === stringVectorComponents.slice( 0, this.components.length ) ) {
  1329. // unnecessary swizzle
  1330. snippet = builder.format( nodeSnippet, type, output );
  1331. } else {
  1332. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1333. }
  1334. } else {
  1335. // ignore .components if .node returns float/integer
  1336. snippet = node.build( builder, output );
  1337. }
  1338. return snippet;
  1339. }
  1340. serialize( data ) {
  1341. super.serialize( data );
  1342. data.components = this.components;
  1343. }
  1344. deserialize( data ) {
  1345. super.deserialize( data );
  1346. this.components = data.components;
  1347. }
  1348. }
  1349. class SetNode extends TempNode {
  1350. static get type() {
  1351. return 'SetNode';
  1352. }
  1353. constructor( sourceNode, components, targetNode ) {
  1354. super();
  1355. this.sourceNode = sourceNode;
  1356. this.components = components;
  1357. this.targetNode = targetNode;
  1358. }
  1359. getNodeType( builder ) {
  1360. return this.sourceNode.getNodeType( builder );
  1361. }
  1362. generate( builder ) {
  1363. const { sourceNode, components, targetNode } = this;
  1364. const sourceType = this.getNodeType( builder );
  1365. const targetType = builder.getTypeFromLength( components.length, targetNode.getNodeType( builder ) );
  1366. const targetSnippet = targetNode.build( builder, targetType );
  1367. const sourceSnippet = sourceNode.build( builder, sourceType );
  1368. const length = builder.getTypeLength( sourceType );
  1369. const snippetValues = [];
  1370. for ( let i = 0; i < length; i ++ ) {
  1371. const component = vectorComponents[ i ];
  1372. if ( component === components[ 0 ] ) {
  1373. snippetValues.push( targetSnippet );
  1374. i += components.length - 1;
  1375. } else {
  1376. snippetValues.push( sourceSnippet + '.' + component );
  1377. }
  1378. }
  1379. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1380. }
  1381. }
  1382. class FlipNode extends TempNode {
  1383. static get type() {
  1384. return 'FlipNode';
  1385. }
  1386. constructor( sourceNode, components ) {
  1387. super();
  1388. this.sourceNode = sourceNode;
  1389. this.components = components;
  1390. }
  1391. getNodeType( builder ) {
  1392. return this.sourceNode.getNodeType( builder );
  1393. }
  1394. generate( builder ) {
  1395. const { components, sourceNode } = this;
  1396. const sourceType = this.getNodeType( builder );
  1397. const sourceSnippet = sourceNode.build( builder );
  1398. const sourceCache = builder.getVarFromNode( this );
  1399. const sourceProperty = builder.getPropertyName( sourceCache );
  1400. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  1401. const length = builder.getTypeLength( sourceType );
  1402. const snippetValues = [];
  1403. let componentIndex = 0;
  1404. for ( let i = 0; i < length; i ++ ) {
  1405. const component = vectorComponents[ i ];
  1406. if ( component === components[ componentIndex ] ) {
  1407. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  1408. componentIndex ++;
  1409. } else {
  1410. snippetValues.push( sourceProperty + '.' + component );
  1411. }
  1412. }
  1413. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1414. }
  1415. }
  1416. /**
  1417. * Base class for representing data input nodes.
  1418. *
  1419. * @augments Node
  1420. */
  1421. class InputNode extends Node {
  1422. static get type() {
  1423. return 'InputNode';
  1424. }
  1425. /**
  1426. * Constructs a new input node.
  1427. *
  1428. * @param {Any} value - The value of this node. This can be a any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  1429. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1430. */
  1431. constructor( value, nodeType = null ) {
  1432. super( nodeType );
  1433. /**
  1434. * This flag can be used for type testing.
  1435. *
  1436. * @type {Boolean}
  1437. * @readonly
  1438. * @default true
  1439. */
  1440. this.isInputNode = true;
  1441. /**
  1442. * The value of this node. This can be a any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  1443. *
  1444. * @type {Any}
  1445. */
  1446. this.value = value;
  1447. /**
  1448. * The precision of the value in the shader.
  1449. *
  1450. * @type {('low'|'medium'|'high')?}
  1451. * @default null
  1452. */
  1453. this.precision = null;
  1454. }
  1455. getNodeType( /*builder*/ ) {
  1456. if ( this.nodeType === null ) {
  1457. return getValueType( this.value );
  1458. }
  1459. return this.nodeType;
  1460. }
  1461. /**
  1462. * Returns the input type of the node which is by default the node type. Derived modules
  1463. * might overwrite this method and use a fixed type or compute one analytically.
  1464. *
  1465. * A typical example for different input and node types are textures. The input type of a
  1466. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  1467. *
  1468. * @param {NodeBuilder} builder - The current node builder.
  1469. * @return {String} The input type.
  1470. */
  1471. getInputType( builder ) {
  1472. return this.getNodeType( builder );
  1473. }
  1474. /**
  1475. * Sets the precision to the given value. The method can be
  1476. * overwritten in derived classes if the final precision must be computed
  1477. * analytically.
  1478. *
  1479. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  1480. * @return {InputNode} A reference to this node.
  1481. */
  1482. setPrecision( precision ) {
  1483. this.precision = precision;
  1484. return this;
  1485. }
  1486. serialize( data ) {
  1487. super.serialize( data );
  1488. data.value = this.value;
  1489. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  1490. data.valueType = getValueType( this.value );
  1491. data.nodeType = this.nodeType;
  1492. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  1493. data.precision = this.precision;
  1494. }
  1495. deserialize( data ) {
  1496. super.deserialize( data );
  1497. this.nodeType = data.nodeType;
  1498. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  1499. this.precision = data.precision || null;
  1500. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  1501. }
  1502. generate( /*builder, output*/ ) {
  1503. console.warn( 'Abstract function.' );
  1504. }
  1505. }
  1506. /**
  1507. * Class for representing a constant value in the shader.
  1508. *
  1509. * @augments InputNode
  1510. */
  1511. class ConstNode extends InputNode {
  1512. static get type() {
  1513. return 'ConstNode';
  1514. }
  1515. /**
  1516. * Constructs a new input node.
  1517. *
  1518. * @param {Any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  1519. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1520. */
  1521. constructor( value, nodeType = null ) {
  1522. super( value, nodeType );
  1523. /**
  1524. * This flag can be used for type testing.
  1525. *
  1526. * @type {Boolean}
  1527. * @readonly
  1528. * @default true
  1529. */
  1530. this.isConstNode = true;
  1531. }
  1532. /**
  1533. * Generates the shader string of the value with the current node builder.
  1534. *
  1535. * @param {NodeBuilder} builder - The current node builder.
  1536. * @return {String} The generated value as a shader string.
  1537. */
  1538. generateConst( builder ) {
  1539. return builder.generateConst( this.getNodeType( builder ), this.value );
  1540. }
  1541. generate( builder, output ) {
  1542. const type = this.getNodeType( builder );
  1543. return builder.format( this.generateConst( builder ), type, output );
  1544. }
  1545. }
  1546. //
  1547. let currentStack = null;
  1548. const NodeElements = new Map();
  1549. function addMethodChaining( name, nodeElement ) {
  1550. if ( NodeElements.has( name ) ) {
  1551. console.warn( `Redefinition of method chaining ${ name }` );
  1552. return;
  1553. }
  1554. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  1555. NodeElements.set( name, nodeElement );
  1556. }
  1557. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  1558. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  1559. const shaderNodeHandler = {
  1560. setup( NodeClosure, params ) {
  1561. const inputs = params.shift();
  1562. return NodeClosure( nodeObjects( inputs ), ...params );
  1563. },
  1564. get( node, prop, nodeObj ) {
  1565. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  1566. if ( node.isStackNode !== true && prop === 'assign' ) {
  1567. return ( ...params ) => {
  1568. currentStack.assign( nodeObj, ...params );
  1569. return nodeObj;
  1570. };
  1571. } else if ( NodeElements.has( prop ) ) {
  1572. const nodeElement = NodeElements.get( prop );
  1573. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  1574. } else if ( prop === 'self' ) {
  1575. return node;
  1576. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  1577. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  1578. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  1579. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  1580. // accessing properties ( swizzle )
  1581. prop = parseSwizzle( prop );
  1582. return nodeObject( new SplitNode( nodeObj, prop ) );
  1583. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  1584. // set properties ( swizzle ) and sort to xyzw sequence
  1585. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  1586. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  1587. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  1588. // set properties ( swizzle ) and sort to xyzw sequence
  1589. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  1590. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  1591. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  1592. // accessing property
  1593. if ( prop === 'width' ) prop = 'x';
  1594. else if ( prop === 'height' ) prop = 'y';
  1595. else if ( prop === 'depth' ) prop = 'z';
  1596. return nodeObject( new SplitNode( node, prop ) );
  1597. } else if ( /^\d+$/.test( prop ) === true ) {
  1598. // accessing array
  1599. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  1600. }
  1601. }
  1602. return Reflect.get( node, prop, nodeObj );
  1603. },
  1604. set( node, prop, value, nodeObj ) {
  1605. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  1606. // setting properties
  1607. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  1608. nodeObj[ prop ].assign( value );
  1609. return true;
  1610. }
  1611. }
  1612. return Reflect.set( node, prop, value, nodeObj );
  1613. }
  1614. };
  1615. const nodeObjectsCacheMap = new WeakMap();
  1616. const nodeBuilderFunctionsCacheMap = new WeakMap();
  1617. const ShaderNodeObject = function ( obj, altType = null ) {
  1618. const type = getValueType( obj );
  1619. if ( type === 'node' ) {
  1620. let nodeObject = nodeObjectsCacheMap.get( obj );
  1621. if ( nodeObject === undefined ) {
  1622. nodeObject = new Proxy( obj, shaderNodeHandler );
  1623. nodeObjectsCacheMap.set( obj, nodeObject );
  1624. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  1625. }
  1626. return nodeObject;
  1627. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  1628. return nodeObject( getConstNode( obj, altType ) );
  1629. } else if ( type === 'shader' ) {
  1630. return Fn( obj );
  1631. }
  1632. return obj;
  1633. };
  1634. const ShaderNodeObjects = function ( objects, altType = null ) {
  1635. for ( const name in objects ) {
  1636. objects[ name ] = nodeObject( objects[ name ], altType );
  1637. }
  1638. return objects;
  1639. };
  1640. const ShaderNodeArray = function ( array, altType = null ) {
  1641. const len = array.length;
  1642. for ( let i = 0; i < len; i ++ ) {
  1643. array[ i ] = nodeObject( array[ i ], altType );
  1644. }
  1645. return array;
  1646. };
  1647. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  1648. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  1649. if ( scope === null ) {
  1650. return ( ...params ) => {
  1651. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  1652. };
  1653. } else if ( factor !== null ) {
  1654. factor = nodeObject( factor );
  1655. return ( ...params ) => {
  1656. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  1657. };
  1658. } else {
  1659. return ( ...params ) => {
  1660. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  1661. };
  1662. }
  1663. };
  1664. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  1665. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  1666. };
  1667. class ShaderCallNodeInternal extends Node {
  1668. constructor( shaderNode, inputNodes ) {
  1669. super();
  1670. this.shaderNode = shaderNode;
  1671. this.inputNodes = inputNodes;
  1672. }
  1673. getNodeType( builder ) {
  1674. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  1675. }
  1676. call( builder ) {
  1677. const { shaderNode, inputNodes } = this;
  1678. const properties = builder.getNodeProperties( shaderNode );
  1679. if ( properties.onceOutput ) return properties.onceOutput;
  1680. //
  1681. let result = null;
  1682. if ( shaderNode.layout ) {
  1683. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  1684. if ( functionNodesCacheMap === undefined ) {
  1685. functionNodesCacheMap = new WeakMap();
  1686. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  1687. }
  1688. let functionNode = functionNodesCacheMap.get( shaderNode );
  1689. if ( functionNode === undefined ) {
  1690. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  1691. functionNodesCacheMap.set( shaderNode, functionNode );
  1692. }
  1693. if ( builder.currentFunctionNode !== null ) {
  1694. builder.currentFunctionNode.includes.push( functionNode );
  1695. }
  1696. result = nodeObject( functionNode.call( inputNodes ) );
  1697. } else {
  1698. const jsFunc = shaderNode.jsFunc;
  1699. const outputNode = inputNodes !== null ? jsFunc( inputNodes, builder ) : jsFunc( builder );
  1700. result = nodeObject( outputNode );
  1701. }
  1702. if ( shaderNode.once ) {
  1703. properties.onceOutput = result;
  1704. }
  1705. return result;
  1706. }
  1707. getOutputNode( builder ) {
  1708. const properties = builder.getNodeProperties( this );
  1709. if ( properties.outputNode === null ) {
  1710. properties.outputNode = this.setupOutput( builder );
  1711. }
  1712. return properties.outputNode;
  1713. }
  1714. setup( builder ) {
  1715. return this.getOutputNode( builder );
  1716. }
  1717. setupOutput( builder ) {
  1718. builder.addStack();
  1719. builder.stack.outputNode = this.call( builder );
  1720. return builder.removeStack();
  1721. }
  1722. generate( builder, output ) {
  1723. const outputNode = this.getOutputNode( builder );
  1724. return outputNode.build( builder, output );
  1725. }
  1726. }
  1727. class ShaderNodeInternal extends Node {
  1728. constructor( jsFunc, nodeType ) {
  1729. super( nodeType );
  1730. this.jsFunc = jsFunc;
  1731. this.layout = null;
  1732. this.global = true;
  1733. this.once = false;
  1734. }
  1735. setLayout( layout ) {
  1736. this.layout = layout;
  1737. return this;
  1738. }
  1739. call( inputs = null ) {
  1740. nodeObjects( inputs );
  1741. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  1742. }
  1743. setup() {
  1744. return this.call();
  1745. }
  1746. }
  1747. const bools = [ false, true ];
  1748. const uints = [ 0, 1, 2, 3 ];
  1749. const ints = [ - 1, - 2 ];
  1750. 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 ];
  1751. const boolsCacheMap = new Map();
  1752. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  1753. const uintsCacheMap = new Map();
  1754. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  1755. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  1756. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  1757. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  1758. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  1759. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  1760. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  1761. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  1762. const getConstNode = ( value, type ) => {
  1763. if ( constNodesCacheMap.has( value ) ) {
  1764. return constNodesCacheMap.get( value );
  1765. } else if ( value.isNode === true ) {
  1766. return value;
  1767. } else {
  1768. return new ConstNode( value, type );
  1769. }
  1770. };
  1771. const safeGetNodeType = ( node ) => {
  1772. try {
  1773. return node.getNodeType();
  1774. } catch ( _ ) {
  1775. return undefined;
  1776. }
  1777. };
  1778. const ConvertType = function ( type, cacheMap = null ) {
  1779. return ( ...params ) => {
  1780. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  1781. params = [ getValueFromType( type, ...params ) ];
  1782. }
  1783. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  1784. return nodeObject( cacheMap.get( params[ 0 ] ) );
  1785. }
  1786. if ( params.length === 1 ) {
  1787. const node = getConstNode( params[ 0 ], type );
  1788. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  1789. return nodeObject( new ConvertNode( node, type ) );
  1790. }
  1791. const nodes = params.map( param => getConstNode( param ) );
  1792. return nodeObject( new JoinNode( nodes, type ) );
  1793. };
  1794. };
  1795. // exports
  1796. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  1797. // utils
  1798. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  1799. // shader node base
  1800. function ShaderNode( jsFunc, nodeType ) {
  1801. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  1802. }
  1803. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  1804. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  1805. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  1806. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  1807. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  1808. const Fn = ( jsFunc, nodeType ) => {
  1809. const shaderNode = new ShaderNode( jsFunc, nodeType );
  1810. const fn = ( ...params ) => {
  1811. let inputs;
  1812. nodeObjects( params );
  1813. if ( params[ 0 ] && params[ 0 ].isNode ) {
  1814. inputs = [ ...params ];
  1815. } else {
  1816. inputs = params[ 0 ];
  1817. }
  1818. return shaderNode.call( inputs );
  1819. };
  1820. fn.shaderNode = shaderNode;
  1821. fn.setLayout = ( layout ) => {
  1822. shaderNode.setLayout( layout );
  1823. return fn;
  1824. };
  1825. fn.once = () => {
  1826. shaderNode.once = true;
  1827. return fn;
  1828. };
  1829. return fn;
  1830. };
  1831. const tslFn = ( ...params ) => { // @deprecated, r168
  1832. console.warn( 'TSL.ShaderNode: tslFn() has been renamed to Fn().' );
  1833. return Fn( ...params );
  1834. };
  1835. //
  1836. addMethodChaining( 'toGlobal', ( node ) => {
  1837. node.global = true;
  1838. return node;
  1839. } );
  1840. //
  1841. const setCurrentStack = ( stack ) => {
  1842. currentStack = stack;
  1843. };
  1844. const getCurrentStack = () => currentStack;
  1845. const If = ( ...params ) => currentStack.If( ...params );
  1846. function append( node ) {
  1847. if ( currentStack ) currentStack.add( node );
  1848. return node;
  1849. }
  1850. addMethodChaining( 'append', append );
  1851. // types
  1852. const color = new ConvertType( 'color' );
  1853. const float = new ConvertType( 'float', cacheMaps.float );
  1854. const int = new ConvertType( 'int', cacheMaps.ints );
  1855. const uint = new ConvertType( 'uint', cacheMaps.uint );
  1856. const bool = new ConvertType( 'bool', cacheMaps.bool );
  1857. const vec2 = new ConvertType( 'vec2' );
  1858. const ivec2 = new ConvertType( 'ivec2' );
  1859. const uvec2 = new ConvertType( 'uvec2' );
  1860. const bvec2 = new ConvertType( 'bvec2' );
  1861. const vec3 = new ConvertType( 'vec3' );
  1862. const ivec3 = new ConvertType( 'ivec3' );
  1863. const uvec3 = new ConvertType( 'uvec3' );
  1864. const bvec3 = new ConvertType( 'bvec3' );
  1865. const vec4 = new ConvertType( 'vec4' );
  1866. const ivec4 = new ConvertType( 'ivec4' );
  1867. const uvec4 = new ConvertType( 'uvec4' );
  1868. const bvec4 = new ConvertType( 'bvec4' );
  1869. const mat2 = new ConvertType( 'mat2' );
  1870. const mat3 = new ConvertType( 'mat3' );
  1871. const mat4 = new ConvertType( 'mat4' );
  1872. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  1873. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  1874. addMethodChaining( 'toColor', color );
  1875. addMethodChaining( 'toFloat', float );
  1876. addMethodChaining( 'toInt', int );
  1877. addMethodChaining( 'toUint', uint );
  1878. addMethodChaining( 'toBool', bool );
  1879. addMethodChaining( 'toVec2', vec2 );
  1880. addMethodChaining( 'toIVec2', ivec2 );
  1881. addMethodChaining( 'toUVec2', uvec2 );
  1882. addMethodChaining( 'toBVec2', bvec2 );
  1883. addMethodChaining( 'toVec3', vec3 );
  1884. addMethodChaining( 'toIVec3', ivec3 );
  1885. addMethodChaining( 'toUVec3', uvec3 );
  1886. addMethodChaining( 'toBVec3', bvec3 );
  1887. addMethodChaining( 'toVec4', vec4 );
  1888. addMethodChaining( 'toIVec4', ivec4 );
  1889. addMethodChaining( 'toUVec4', uvec4 );
  1890. addMethodChaining( 'toBVec4', bvec4 );
  1891. addMethodChaining( 'toMat2', mat2 );
  1892. addMethodChaining( 'toMat3', mat3 );
  1893. addMethodChaining( 'toMat4', mat4 );
  1894. // basic nodes
  1895. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode );
  1896. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  1897. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  1898. addMethodChaining( 'element', element );
  1899. addMethodChaining( 'convert', convert );
  1900. /**
  1901. * This node can be used to group single instances of {@link UniformNode}
  1902. * and manage them as a uniform buffer.
  1903. *
  1904. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  1905. * will be used when defining the {@link UniformNode#groupNode} property.
  1906. *
  1907. * - `objectGroup`: Uniform buffer per object.
  1908. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  1909. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  1910. *
  1911. * @augments Node
  1912. */
  1913. class UniformGroupNode extends Node {
  1914. static get type() {
  1915. return 'UniformGroupNode';
  1916. }
  1917. /**
  1918. * Constructs a new uniform group node.
  1919. *
  1920. * @param {String} name - The name of the uniform group node.
  1921. * @param {Boolean} [shared=false] - Whether this uniform group node is shared or not.
  1922. * @param {Number} [order=1] - Influences the internal sorting.
  1923. */
  1924. constructor( name, shared = false, order = 1 ) {
  1925. super( 'string' );
  1926. /**
  1927. * The name of the uniform group node.
  1928. *
  1929. * @type {String}
  1930. */
  1931. this.name = name;
  1932. /**
  1933. * Whether this uniform group node is shared or not.
  1934. *
  1935. * @type {Boolean}
  1936. * @default false
  1937. */
  1938. this.shared = shared;
  1939. /**
  1940. * Influences the internal sorting.
  1941. * TODO: Add details when this property should be changed.
  1942. *
  1943. * @type {Number}
  1944. * @default 1
  1945. */
  1946. this.order = order;
  1947. /**
  1948. * This flag can be used for type testing.
  1949. *
  1950. * @type {Boolean}
  1951. * @readonly
  1952. * @default true
  1953. */
  1954. this.isUniformGroup = true;
  1955. }
  1956. serialize( data ) {
  1957. super.serialize( data );
  1958. data.name = this.name;
  1959. data.version = this.version;
  1960. data.shared = this.shared;
  1961. }
  1962. deserialize( data ) {
  1963. super.deserialize( data );
  1964. this.name = data.name;
  1965. this.version = data.version;
  1966. this.shared = data.shared;
  1967. }
  1968. }
  1969. const uniformGroup = ( name ) => new UniformGroupNode( name );
  1970. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  1971. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  1972. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  1973. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  1974. /**
  1975. * Class for representing a uniform.
  1976. *
  1977. * @augments InputNode
  1978. */
  1979. class UniformNode extends InputNode {
  1980. static get type() {
  1981. return 'UniformNode';
  1982. }
  1983. /**
  1984. * Constructs a new uniform node.
  1985. *
  1986. * @param {Any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  1987. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1988. */
  1989. constructor( value, nodeType = null ) {
  1990. super( value, nodeType );
  1991. /**
  1992. * This flag can be used for type testing.
  1993. *
  1994. * @type {Boolean}
  1995. * @readonly
  1996. * @default true
  1997. */
  1998. this.isUniformNode = true;
  1999. /**
  2000. * The name or label of the uniform.
  2001. *
  2002. * @type {String}
  2003. * @default ''
  2004. */
  2005. this.name = '';
  2006. /**
  2007. * The uniform group of this uniform. By default, uniforms are
  2008. * managed per object but they might belong to a shared group
  2009. * which is updated per frame or render call.
  2010. *
  2011. * @type {UniformGroupNode}
  2012. */
  2013. this.groupNode = objectGroup;
  2014. }
  2015. /**
  2016. * Sets the {@link UniformNode#name} property.
  2017. *
  2018. * @param {String} name - The name of the uniform.
  2019. * @return {UniformNode} A reference to this node.
  2020. */
  2021. label( name ) {
  2022. this.name = name;
  2023. return this;
  2024. }
  2025. /**
  2026. * Sets the {@link UniformNode#groupNode} property.
  2027. *
  2028. * @param {UniformGroupNode} group - The uniform group.
  2029. * @return {UniformNode} A reference to this node.
  2030. */
  2031. setGroup( group ) {
  2032. this.groupNode = group;
  2033. return this;
  2034. }
  2035. /**
  2036. * Returns the {@link UniformNode#groupNode}.
  2037. *
  2038. * @return {UniformGroupNode} The uniform group.
  2039. */
  2040. getGroup() {
  2041. return this.groupNode;
  2042. }
  2043. /**
  2044. * By default, this method returns the result of {@link Node#getHash} but derived
  2045. * classes might overwrite this method with a different implementation.
  2046. *
  2047. * @param {NodeBuilder} builder - The current node builder.
  2048. * @return {String} The uniform hash.
  2049. */
  2050. getUniformHash( builder ) {
  2051. return this.getHash( builder );
  2052. }
  2053. onUpdate( callback, updateType ) {
  2054. const self = this.getSelf();
  2055. callback = callback.bind( self );
  2056. return super.onUpdate( ( frame ) => {
  2057. const value = callback( frame, self );
  2058. if ( value !== undefined ) {
  2059. this.value = value;
  2060. }
  2061. }, updateType );
  2062. }
  2063. generate( builder, output ) {
  2064. const type = this.getNodeType( builder );
  2065. const hash = this.getUniformHash( builder );
  2066. let sharedNode = builder.getNodeFromHash( hash );
  2067. if ( sharedNode === undefined ) {
  2068. builder.setHashNode( this, hash );
  2069. sharedNode = this;
  2070. }
  2071. const sharedNodeType = sharedNode.getInputType( builder );
  2072. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  2073. const propertyName = builder.getPropertyName( nodeUniform );
  2074. if ( builder.context.label !== undefined ) delete builder.context.label;
  2075. return builder.format( propertyName, type, output );
  2076. }
  2077. }
  2078. const uniform = ( arg1, arg2 ) => {
  2079. const nodeType = getConstNodeType( arg2 || arg1 );
  2080. // @TODO: get ConstNode from .traverse() in the future
  2081. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  2082. return nodeObject( new UniformNode( value, nodeType ) );
  2083. };
  2084. class PropertyNode extends Node {
  2085. static get type() {
  2086. return 'PropertyNode';
  2087. }
  2088. constructor( nodeType, name = null, varying = false ) {
  2089. super( nodeType );
  2090. this.name = name;
  2091. this.varying = varying;
  2092. this.isPropertyNode = true;
  2093. }
  2094. getHash( builder ) {
  2095. return this.name || super.getHash( builder );
  2096. }
  2097. isGlobal( /*builder*/ ) {
  2098. return true;
  2099. }
  2100. generate( builder ) {
  2101. let nodeVar;
  2102. if ( this.varying === true ) {
  2103. nodeVar = builder.getVaryingFromNode( this, this.name );
  2104. nodeVar.needsInterpolation = true;
  2105. } else {
  2106. nodeVar = builder.getVarFromNode( this, this.name );
  2107. }
  2108. return builder.getPropertyName( nodeVar );
  2109. }
  2110. }
  2111. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2112. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2113. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2114. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  2115. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  2116. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  2117. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  2118. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  2119. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  2120. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  2121. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  2122. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  2123. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  2124. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  2125. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  2126. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  2127. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  2128. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  2129. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  2130. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  2131. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  2132. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  2133. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  2134. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  2135. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  2136. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  2137. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  2138. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  2139. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  2140. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  2141. /**
  2142. * These node represents an assign operation. Meaning a node is assigned
  2143. * to another node.
  2144. *
  2145. * @augments TempNode
  2146. */
  2147. class AssignNode extends TempNode {
  2148. static get type() {
  2149. return 'AssignNode';
  2150. }
  2151. /**
  2152. * Constructs a new assign node.
  2153. *
  2154. * @param {Node} targetNode - The target node.
  2155. * @param {Node} sourceNode - The source type.
  2156. */
  2157. constructor( targetNode, sourceNode ) {
  2158. super();
  2159. /**
  2160. * The target node.
  2161. *
  2162. * @type {Node}
  2163. */
  2164. this.targetNode = targetNode;
  2165. /**
  2166. * The source node.
  2167. *
  2168. * @type {Node}
  2169. */
  2170. this.sourceNode = sourceNode;
  2171. }
  2172. /**
  2173. * Whether this node is used more than once in context of other nodes. This method
  2174. * is overwritten since it always returns `false` (assigns are unique).
  2175. *
  2176. * @return {Boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  2177. */
  2178. hasDependencies() {
  2179. return false;
  2180. }
  2181. getNodeType( builder, output ) {
  2182. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  2183. }
  2184. /**
  2185. * Whether a split is required when assigning source to target. This can happen when the component length of
  2186. * target and source data type does not match.
  2187. *
  2188. * @param {NodeBuilder} builder - The current node builder.
  2189. * @return {Boolean} Whether a split is required when assigning source to target.
  2190. */
  2191. needsSplitAssign( builder ) {
  2192. const { targetNode } = this;
  2193. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  2194. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  2195. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  2196. return assignDifferentVector;
  2197. }
  2198. return false;
  2199. }
  2200. generate( builder, output ) {
  2201. const { targetNode, sourceNode } = this;
  2202. const needsSplitAssign = this.needsSplitAssign( builder );
  2203. const targetType = targetNode.getNodeType( builder );
  2204. const target = targetNode.context( { assign: true } ).build( builder );
  2205. const source = sourceNode.build( builder, targetType );
  2206. const sourceType = sourceNode.getNodeType( builder );
  2207. const nodeData = builder.getDataFromNode( this );
  2208. //
  2209. let snippet;
  2210. if ( nodeData.initialized === true ) {
  2211. if ( output !== 'void' ) {
  2212. snippet = target;
  2213. }
  2214. } else if ( needsSplitAssign ) {
  2215. const sourceVar = builder.getVarFromNode( this, null, targetType );
  2216. const sourceProperty = builder.getPropertyName( sourceVar );
  2217. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  2218. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  2219. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  2220. const component = targetNode.components[ i ];
  2221. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  2222. }
  2223. if ( output !== 'void' ) {
  2224. snippet = target;
  2225. }
  2226. } else {
  2227. snippet = `${ target } = ${ source }`;
  2228. if ( output === 'void' || sourceType === 'void' ) {
  2229. builder.addLineFlowCode( snippet, this );
  2230. if ( output !== 'void' ) {
  2231. snippet = target;
  2232. }
  2233. }
  2234. }
  2235. nodeData.initialized = true;
  2236. return builder.format( snippet, targetType, output );
  2237. }
  2238. }
  2239. const assign = /*@__PURE__*/ nodeProxy( AssignNode );
  2240. addMethodChaining( 'assign', assign );
  2241. /**
  2242. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  2243. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  2244. * this logic.
  2245. *
  2246. * @augments TempNode
  2247. */
  2248. class FunctionCallNode extends TempNode {
  2249. static get type() {
  2250. return 'FunctionCallNode';
  2251. }
  2252. /**
  2253. * Constructs a new function call node.
  2254. *
  2255. * @param {FunctionNode?} functionNode - The function node.
  2256. * @param {Object<String, Node>} [parameters={}] - The parameters for the function call.
  2257. */
  2258. constructor( functionNode = null, parameters = {} ) {
  2259. super();
  2260. /**
  2261. * The function node.
  2262. *
  2263. * @type {FunctionNode}
  2264. * @default null
  2265. */
  2266. this.functionNode = functionNode;
  2267. /**
  2268. * The parameters of the function call.
  2269. *
  2270. * @type {Object<String, Node>}
  2271. * @default {}
  2272. */
  2273. this.parameters = parameters;
  2274. }
  2275. /**
  2276. * Sets the parameters of the function call node.
  2277. *
  2278. * @param {Object<String, Node>} parameters - The parameters to set.
  2279. * @return {FunctionCallNode} A reference to this node.
  2280. */
  2281. setParameters( parameters ) {
  2282. this.parameters = parameters;
  2283. return this;
  2284. }
  2285. /**
  2286. * Returns the parameters of the function call node.
  2287. *
  2288. * @return {Object<String, Node>} The parameters of this node.
  2289. */
  2290. getParameters() {
  2291. return this.parameters;
  2292. }
  2293. getNodeType( builder ) {
  2294. return this.functionNode.getNodeType( builder );
  2295. }
  2296. generate( builder ) {
  2297. const params = [];
  2298. const functionNode = this.functionNode;
  2299. const inputs = functionNode.getInputs( builder );
  2300. const parameters = this.parameters;
  2301. const generateInput = ( node, inputNode ) => {
  2302. const type = inputNode.type;
  2303. const pointer = type === 'pointer';
  2304. let output;
  2305. if ( pointer ) output = '&' + node.build( builder );
  2306. else output = node.build( builder, type );
  2307. return output;
  2308. };
  2309. if ( Array.isArray( parameters ) ) {
  2310. for ( let i = 0; i < parameters.length; i ++ ) {
  2311. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  2312. }
  2313. } else {
  2314. for ( const inputNode of inputs ) {
  2315. const node = parameters[ inputNode.name ];
  2316. if ( node !== undefined ) {
  2317. params.push( generateInput( node, inputNode ) );
  2318. } else {
  2319. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  2320. }
  2321. }
  2322. }
  2323. const functionName = functionNode.build( builder, 'property' );
  2324. return `${functionName}( ${params.join( ', ' )} )`;
  2325. }
  2326. }
  2327. const call = ( func, ...params ) => {
  2328. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  2329. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  2330. };
  2331. addMethodChaining( 'call', call );
  2332. class OperatorNode extends TempNode {
  2333. static get type() {
  2334. return 'OperatorNode';
  2335. }
  2336. constructor( op, aNode, bNode, ...params ) {
  2337. super();
  2338. if ( params.length > 0 ) {
  2339. let finalOp = new OperatorNode( op, aNode, bNode );
  2340. for ( let i = 0; i < params.length - 1; i ++ ) {
  2341. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  2342. }
  2343. aNode = finalOp;
  2344. bNode = params[ params.length - 1 ];
  2345. }
  2346. this.op = op;
  2347. this.aNode = aNode;
  2348. this.bNode = bNode;
  2349. }
  2350. getNodeType( builder, output ) {
  2351. const op = this.op;
  2352. const aNode = this.aNode;
  2353. const bNode = this.bNode;
  2354. const typeA = aNode.getNodeType( builder );
  2355. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  2356. if ( typeA === 'void' || typeB === 'void' ) {
  2357. return 'void';
  2358. } else if ( op === '%' ) {
  2359. return typeA;
  2360. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  2361. return builder.getIntegerType( typeA );
  2362. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  2363. return 'bool';
  2364. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  2365. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  2366. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  2367. } else {
  2368. if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  2369. return typeB;
  2370. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  2371. // matrix x vector
  2372. return builder.getVectorFromMatrix( typeA );
  2373. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  2374. // vector x matrix
  2375. return builder.getVectorFromMatrix( typeB );
  2376. } else if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  2377. // anytype x anytype: use the greater length vector
  2378. return typeB;
  2379. }
  2380. return typeA;
  2381. }
  2382. }
  2383. generate( builder, output ) {
  2384. const op = this.op;
  2385. const aNode = this.aNode;
  2386. const bNode = this.bNode;
  2387. const type = this.getNodeType( builder, output );
  2388. let typeA = null;
  2389. let typeB = null;
  2390. if ( type !== 'void' ) {
  2391. typeA = aNode.getNodeType( builder );
  2392. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  2393. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  2394. if ( builder.isVector( typeA ) ) {
  2395. typeB = typeA;
  2396. } else if ( typeA !== typeB ) {
  2397. typeA = typeB = 'float';
  2398. }
  2399. } else if ( op === '>>' || op === '<<' ) {
  2400. typeA = type;
  2401. typeB = builder.changeComponentType( typeB, 'uint' );
  2402. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  2403. // matrix x vector
  2404. typeB = builder.getVectorFromMatrix( typeA );
  2405. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  2406. // vector x matrix
  2407. typeA = builder.getVectorFromMatrix( typeB );
  2408. } else {
  2409. // anytype x anytype
  2410. typeA = typeB = type;
  2411. }
  2412. } else {
  2413. typeA = typeB = type;
  2414. }
  2415. const a = aNode.build( builder, typeA );
  2416. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  2417. const outputLength = builder.getTypeLength( output );
  2418. const fnOpSnippet = builder.getFunctionOperator( op );
  2419. if ( output !== 'void' ) {
  2420. if ( op === '<' && outputLength > 1 ) {
  2421. if ( builder.useComparisonMethod ) {
  2422. return builder.format( `${ builder.getMethod( 'lessThan', output ) }( ${ a }, ${ b } )`, type, output );
  2423. } else {
  2424. return builder.format( `( ${ a } < ${ b } )`, type, output );
  2425. }
  2426. } else if ( op === '<=' && outputLength > 1 ) {
  2427. if ( builder.useComparisonMethod ) {
  2428. return builder.format( `${ builder.getMethod( 'lessThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  2429. } else {
  2430. return builder.format( `( ${ a } <= ${ b } )`, type, output );
  2431. }
  2432. } else if ( op === '>' && outputLength > 1 ) {
  2433. if ( builder.useComparisonMethod ) {
  2434. return builder.format( `${ builder.getMethod( 'greaterThan', output ) }( ${ a }, ${ b } )`, type, output );
  2435. } else {
  2436. return builder.format( `( ${ a } > ${ b } )`, type, output );
  2437. }
  2438. } else if ( op === '>=' && outputLength > 1 ) {
  2439. if ( builder.useComparisonMethod ) {
  2440. return builder.format( `${ builder.getMethod( 'greaterThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  2441. } else {
  2442. return builder.format( `( ${ a } >= ${ b } )`, type, output );
  2443. }
  2444. } else if ( op === '!' || op === '~' ) {
  2445. return builder.format( `(${op}${a})`, typeA, output );
  2446. } else if ( fnOpSnippet ) {
  2447. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  2448. } else {
  2449. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  2450. }
  2451. } else if ( typeA !== 'void' ) {
  2452. if ( fnOpSnippet ) {
  2453. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  2454. } else {
  2455. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  2456. }
  2457. }
  2458. }
  2459. serialize( data ) {
  2460. super.serialize( data );
  2461. data.op = this.op;
  2462. }
  2463. deserialize( data ) {
  2464. super.deserialize( data );
  2465. this.op = data.op;
  2466. }
  2467. }
  2468. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' );
  2469. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' );
  2470. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' );
  2471. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' );
  2472. const modInt = /*@__PURE__*/ nodeProxy( OperatorNode, '%' );
  2473. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' );
  2474. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' );
  2475. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' );
  2476. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' );
  2477. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' );
  2478. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' );
  2479. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' );
  2480. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' );
  2481. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' );
  2482. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' );
  2483. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' );
  2484. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' );
  2485. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' );
  2486. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' );
  2487. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' );
  2488. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' );
  2489. addMethodChaining( 'add', add );
  2490. addMethodChaining( 'sub', sub );
  2491. addMethodChaining( 'mul', mul );
  2492. addMethodChaining( 'div', div );
  2493. addMethodChaining( 'modInt', modInt );
  2494. addMethodChaining( 'equal', equal );
  2495. addMethodChaining( 'notEqual', notEqual );
  2496. addMethodChaining( 'lessThan', lessThan );
  2497. addMethodChaining( 'greaterThan', greaterThan );
  2498. addMethodChaining( 'lessThanEqual', lessThanEqual );
  2499. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  2500. addMethodChaining( 'and', and );
  2501. addMethodChaining( 'or', or );
  2502. addMethodChaining( 'not', not );
  2503. addMethodChaining( 'xor', xor );
  2504. addMethodChaining( 'bitAnd', bitAnd );
  2505. addMethodChaining( 'bitNot', bitNot );
  2506. addMethodChaining( 'bitOr', bitOr );
  2507. addMethodChaining( 'bitXor', bitXor );
  2508. addMethodChaining( 'shiftLeft', shiftLeft );
  2509. addMethodChaining( 'shiftRight', shiftRight );
  2510. const remainder = ( ...params ) => { // @deprecated, r168
  2511. console.warn( 'TSL.OperatorNode: .remainder() has been renamed to .modInt().' );
  2512. return modInt( ...params );
  2513. };
  2514. addMethodChaining( 'remainder', remainder );
  2515. class MathNode extends TempNode {
  2516. static get type() {
  2517. return 'MathNode';
  2518. }
  2519. constructor( method, aNode, bNode = null, cNode = null ) {
  2520. super();
  2521. this.method = method;
  2522. this.aNode = aNode;
  2523. this.bNode = bNode;
  2524. this.cNode = cNode;
  2525. }
  2526. getInputType( builder ) {
  2527. const aType = this.aNode.getNodeType( builder );
  2528. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  2529. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  2530. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  2531. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  2532. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  2533. if ( aLen > bLen && aLen > cLen ) {
  2534. return aType;
  2535. } else if ( bLen > cLen ) {
  2536. return bType;
  2537. } else if ( cLen > aLen ) {
  2538. return cType;
  2539. }
  2540. return aType;
  2541. }
  2542. getNodeType( builder ) {
  2543. const method = this.method;
  2544. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  2545. return 'float';
  2546. } else if ( method === MathNode.CROSS ) {
  2547. return 'vec3';
  2548. } else if ( method === MathNode.ALL ) {
  2549. return 'bool';
  2550. } else if ( method === MathNode.EQUALS ) {
  2551. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  2552. } else if ( method === MathNode.MOD ) {
  2553. return this.aNode.getNodeType( builder );
  2554. } else {
  2555. return this.getInputType( builder );
  2556. }
  2557. }
  2558. generate( builder, output ) {
  2559. const method = this.method;
  2560. const type = this.getNodeType( builder );
  2561. const inputType = this.getInputType( builder );
  2562. const a = this.aNode;
  2563. const b = this.bNode;
  2564. const c = this.cNode;
  2565. const isWebGL = builder.renderer.isWebGLRenderer === true;
  2566. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  2567. // dir can be either a direction vector or a normal vector
  2568. // upper-left 3x3 of matrix is assumed to be orthogonal
  2569. let tA = a;
  2570. let tB = b;
  2571. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  2572. tB = vec4( vec3( tB ), 0.0 );
  2573. } else {
  2574. tA = vec4( vec3( tA ), 0.0 );
  2575. }
  2576. const mulNode = mul( tA, tB ).xyz;
  2577. return normalize( mulNode ).build( builder, output );
  2578. } else if ( method === MathNode.NEGATE ) {
  2579. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  2580. } else if ( method === MathNode.ONE_MINUS ) {
  2581. return sub( 1.0, a ).build( builder, output );
  2582. } else if ( method === MathNode.RECIPROCAL ) {
  2583. return div( 1.0, a ).build( builder, output );
  2584. } else if ( method === MathNode.DIFFERENCE ) {
  2585. return abs( sub( a, b ) ).build( builder, output );
  2586. } else {
  2587. const params = [];
  2588. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  2589. params.push(
  2590. a.build( builder, type ),
  2591. b.build( builder, type )
  2592. );
  2593. } else if ( isWebGL && method === MathNode.STEP ) {
  2594. params.push(
  2595. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  2596. b.build( builder, inputType )
  2597. );
  2598. } else if ( ( isWebGL && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  2599. params.push(
  2600. a.build( builder, inputType ),
  2601. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  2602. );
  2603. } else if ( method === MathNode.REFRACT ) {
  2604. params.push(
  2605. a.build( builder, inputType ),
  2606. b.build( builder, inputType ),
  2607. c.build( builder, 'float' )
  2608. );
  2609. } else if ( method === MathNode.MIX ) {
  2610. params.push(
  2611. a.build( builder, inputType ),
  2612. b.build( builder, inputType ),
  2613. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  2614. );
  2615. } else {
  2616. params.push( a.build( builder, inputType ) );
  2617. if ( b !== null ) params.push( b.build( builder, inputType ) );
  2618. if ( c !== null ) params.push( c.build( builder, inputType ) );
  2619. }
  2620. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  2621. }
  2622. }
  2623. serialize( data ) {
  2624. super.serialize( data );
  2625. data.method = this.method;
  2626. }
  2627. deserialize( data ) {
  2628. super.deserialize( data );
  2629. this.method = data.method;
  2630. }
  2631. }
  2632. // 1 input
  2633. MathNode.ALL = 'all';
  2634. MathNode.ANY = 'any';
  2635. MathNode.EQUALS = 'equals';
  2636. MathNode.RADIANS = 'radians';
  2637. MathNode.DEGREES = 'degrees';
  2638. MathNode.EXP = 'exp';
  2639. MathNode.EXP2 = 'exp2';
  2640. MathNode.LOG = 'log';
  2641. MathNode.LOG2 = 'log2';
  2642. MathNode.SQRT = 'sqrt';
  2643. MathNode.INVERSE_SQRT = 'inversesqrt';
  2644. MathNode.FLOOR = 'floor';
  2645. MathNode.CEIL = 'ceil';
  2646. MathNode.NORMALIZE = 'normalize';
  2647. MathNode.FRACT = 'fract';
  2648. MathNode.SIN = 'sin';
  2649. MathNode.COS = 'cos';
  2650. MathNode.TAN = 'tan';
  2651. MathNode.ASIN = 'asin';
  2652. MathNode.ACOS = 'acos';
  2653. MathNode.ATAN = 'atan';
  2654. MathNode.ABS = 'abs';
  2655. MathNode.SIGN = 'sign';
  2656. MathNode.LENGTH = 'length';
  2657. MathNode.NEGATE = 'negate';
  2658. MathNode.ONE_MINUS = 'oneMinus';
  2659. MathNode.DFDX = 'dFdx';
  2660. MathNode.DFDY = 'dFdy';
  2661. MathNode.ROUND = 'round';
  2662. MathNode.RECIPROCAL = 'reciprocal';
  2663. MathNode.TRUNC = 'trunc';
  2664. MathNode.FWIDTH = 'fwidth';
  2665. MathNode.BITCAST = 'bitcast';
  2666. MathNode.TRANSPOSE = 'transpose';
  2667. // 2 inputs
  2668. MathNode.ATAN2 = 'atan2';
  2669. MathNode.MIN = 'min';
  2670. MathNode.MAX = 'max';
  2671. MathNode.MOD = 'mod';
  2672. MathNode.STEP = 'step';
  2673. MathNode.REFLECT = 'reflect';
  2674. MathNode.DISTANCE = 'distance';
  2675. MathNode.DIFFERENCE = 'difference';
  2676. MathNode.DOT = 'dot';
  2677. MathNode.CROSS = 'cross';
  2678. MathNode.POW = 'pow';
  2679. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  2680. // 3 inputs
  2681. MathNode.MIX = 'mix';
  2682. MathNode.CLAMP = 'clamp';
  2683. MathNode.REFRACT = 'refract';
  2684. MathNode.SMOOTHSTEP = 'smoothstep';
  2685. MathNode.FACEFORWARD = 'faceforward';
  2686. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  2687. const INFINITY = /*@__PURE__*/ float( 1e6 );
  2688. const PI = /*@__PURE__*/ float( Math.PI );
  2689. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  2690. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL );
  2691. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY );
  2692. const equals = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EQUALS );
  2693. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS );
  2694. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES );
  2695. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP );
  2696. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 );
  2697. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG );
  2698. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 );
  2699. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT );
  2700. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  2701. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR );
  2702. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL );
  2703. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE );
  2704. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT );
  2705. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN );
  2706. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS );
  2707. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN );
  2708. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN );
  2709. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS );
  2710. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN );
  2711. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS );
  2712. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN );
  2713. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH );
  2714. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE );
  2715. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS );
  2716. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX );
  2717. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY );
  2718. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND );
  2719. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL );
  2720. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC );
  2721. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH );
  2722. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST );
  2723. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE );
  2724. const atan2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN2 );
  2725. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN );
  2726. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX );
  2727. const mod = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MOD );
  2728. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP );
  2729. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT );
  2730. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE );
  2731. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE );
  2732. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT );
  2733. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS );
  2734. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW );
  2735. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 );
  2736. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 );
  2737. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 );
  2738. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  2739. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  2740. const lengthSq = ( a ) => dot( a, a );
  2741. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX );
  2742. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  2743. const saturate = ( value ) => clamp( value );
  2744. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT );
  2745. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  2746. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD );
  2747. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  2748. const a = 12.9898, b = 78.233, c = 43758.5453;
  2749. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  2750. return fract( sin( sn ).mul( c ) );
  2751. } );
  2752. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  2753. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  2754. addMethodChaining( 'all', all );
  2755. addMethodChaining( 'any', any );
  2756. addMethodChaining( 'equals', equals );
  2757. addMethodChaining( 'radians', radians );
  2758. addMethodChaining( 'degrees', degrees );
  2759. addMethodChaining( 'exp', exp );
  2760. addMethodChaining( 'exp2', exp2 );
  2761. addMethodChaining( 'log', log );
  2762. addMethodChaining( 'log2', log2 );
  2763. addMethodChaining( 'sqrt', sqrt );
  2764. addMethodChaining( 'inverseSqrt', inverseSqrt );
  2765. addMethodChaining( 'floor', floor );
  2766. addMethodChaining( 'ceil', ceil );
  2767. addMethodChaining( 'normalize', normalize );
  2768. addMethodChaining( 'fract', fract );
  2769. addMethodChaining( 'sin', sin );
  2770. addMethodChaining( 'cos', cos );
  2771. addMethodChaining( 'tan', tan );
  2772. addMethodChaining( 'asin', asin );
  2773. addMethodChaining( 'acos', acos );
  2774. addMethodChaining( 'atan', atan );
  2775. addMethodChaining( 'abs', abs );
  2776. addMethodChaining( 'sign', sign );
  2777. addMethodChaining( 'length', length );
  2778. addMethodChaining( 'lengthSq', lengthSq );
  2779. addMethodChaining( 'negate', negate );
  2780. addMethodChaining( 'oneMinus', oneMinus );
  2781. addMethodChaining( 'dFdx', dFdx );
  2782. addMethodChaining( 'dFdy', dFdy );
  2783. addMethodChaining( 'round', round );
  2784. addMethodChaining( 'reciprocal', reciprocal );
  2785. addMethodChaining( 'trunc', trunc );
  2786. addMethodChaining( 'fwidth', fwidth );
  2787. addMethodChaining( 'atan2', atan2 );
  2788. addMethodChaining( 'min', min$1 );
  2789. addMethodChaining( 'max', max$1 );
  2790. addMethodChaining( 'mod', mod );
  2791. addMethodChaining( 'step', step );
  2792. addMethodChaining( 'reflect', reflect );
  2793. addMethodChaining( 'distance', distance );
  2794. addMethodChaining( 'dot', dot );
  2795. addMethodChaining( 'cross', cross );
  2796. addMethodChaining( 'pow', pow );
  2797. addMethodChaining( 'pow2', pow2 );
  2798. addMethodChaining( 'pow3', pow3 );
  2799. addMethodChaining( 'pow4', pow4 );
  2800. addMethodChaining( 'transformDirection', transformDirection );
  2801. addMethodChaining( 'mix', mixElement );
  2802. addMethodChaining( 'clamp', clamp );
  2803. addMethodChaining( 'refract', refract );
  2804. addMethodChaining( 'smoothstep', smoothstepElement );
  2805. addMethodChaining( 'faceForward', faceForward );
  2806. addMethodChaining( 'difference', difference );
  2807. addMethodChaining( 'saturate', saturate );
  2808. addMethodChaining( 'cbrt', cbrt );
  2809. addMethodChaining( 'transpose', transpose );
  2810. addMethodChaining( 'rand', rand );
  2811. class ConditionalNode extends Node {
  2812. static get type() {
  2813. return 'ConditionalNode';
  2814. }
  2815. constructor( condNode, ifNode, elseNode = null ) {
  2816. super();
  2817. this.condNode = condNode;
  2818. this.ifNode = ifNode;
  2819. this.elseNode = elseNode;
  2820. }
  2821. getNodeType( builder ) {
  2822. const ifType = this.ifNode.getNodeType( builder );
  2823. if ( this.elseNode !== null ) {
  2824. const elseType = this.elseNode.getNodeType( builder );
  2825. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  2826. return elseType;
  2827. }
  2828. }
  2829. return ifType;
  2830. }
  2831. setup( builder ) {
  2832. const condNode = this.condNode.cache();
  2833. const ifNode = this.ifNode.cache();
  2834. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  2835. //
  2836. const currentNodeBlock = builder.context.nodeBlock;
  2837. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  2838. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  2839. //
  2840. const properties = builder.getNodeProperties( this );
  2841. properties.condNode = condNode;
  2842. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  2843. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  2844. }
  2845. generate( builder, output ) {
  2846. const type = this.getNodeType( builder );
  2847. const nodeData = builder.getDataFromNode( this );
  2848. if ( nodeData.nodeProperty !== undefined ) {
  2849. return nodeData.nodeProperty;
  2850. }
  2851. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  2852. const needsOutput = output !== 'void';
  2853. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  2854. nodeData.nodeProperty = nodeProperty;
  2855. const nodeSnippet = condNode.build( builder, 'bool' );
  2856. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  2857. let ifSnippet = ifNode.build( builder, type );
  2858. if ( ifSnippet ) {
  2859. if ( needsOutput ) {
  2860. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  2861. } else {
  2862. ifSnippet = 'return ' + ifSnippet + ';';
  2863. }
  2864. }
  2865. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  2866. if ( elseNode !== null ) {
  2867. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  2868. let elseSnippet = elseNode.build( builder, type );
  2869. if ( elseSnippet ) {
  2870. if ( needsOutput ) {
  2871. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  2872. } else {
  2873. elseSnippet = 'return ' + elseSnippet + ';';
  2874. }
  2875. }
  2876. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  2877. } else {
  2878. builder.addFlowCode( '\n\n' );
  2879. }
  2880. return builder.format( nodeProperty, type, output );
  2881. }
  2882. }
  2883. const select = /*@__PURE__*/ nodeProxy( ConditionalNode );
  2884. addMethodChaining( 'select', select );
  2885. //
  2886. const cond = ( ...params ) => { // @deprecated, r168
  2887. console.warn( 'TSL.ConditionalNode: cond() has been renamed to select().' );
  2888. return select( ...params );
  2889. };
  2890. addMethodChaining( 'cond', cond );
  2891. /**
  2892. * This node can be used as a context management component for another node.
  2893. * {@link NodeBuilder} performs its node building process in a specific context and
  2894. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  2895. *
  2896. * ```js
  2897. *node.context( { getUV: () => customCoord } );
  2898. *```
  2899. * @augments Node
  2900. */
  2901. class ContextNode extends Node {
  2902. static get type() {
  2903. return 'ContextNode';
  2904. }
  2905. /**
  2906. * Constructs a new context node.
  2907. *
  2908. * @param {Node} node - The node whose context should be modified.
  2909. * @param {Object} [value={}] - The modified context data.
  2910. */
  2911. constructor( node, value = {} ) {
  2912. super();
  2913. /**
  2914. * This flag can be used for type testing.
  2915. *
  2916. * @type {Boolean}
  2917. * @readonly
  2918. * @default true
  2919. */
  2920. this.isContextNode = true;
  2921. /**
  2922. * The node whose context should be modified.
  2923. *
  2924. * @type {Node}
  2925. */
  2926. this.node = node;
  2927. /**
  2928. * The modified context data.
  2929. *
  2930. * @type {Object}
  2931. * @default {}
  2932. */
  2933. this.value = value;
  2934. }
  2935. /**
  2936. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  2937. *
  2938. * @return {Node} A reference to {@link ContextNode#node}.
  2939. */
  2940. getScope() {
  2941. return this.node.getScope();
  2942. }
  2943. /**
  2944. * This method is overwritten to ensure it returns the type to {@link ContextNode#node}.
  2945. *
  2946. * @param {NodeBuilder} builder - The current node builder.
  2947. * @return {String} The type of {@link ContextNode#node}.
  2948. */
  2949. getNodeType( builder ) {
  2950. return this.node.getNodeType( builder );
  2951. }
  2952. analyze( builder ) {
  2953. this.node.build( builder );
  2954. }
  2955. setup( builder ) {
  2956. const previousContext = builder.getContext();
  2957. builder.setContext( { ...builder.context, ...this.value } );
  2958. const node = this.node.build( builder );
  2959. builder.setContext( previousContext );
  2960. return node;
  2961. }
  2962. generate( builder, output ) {
  2963. const previousContext = builder.getContext();
  2964. builder.setContext( { ...builder.context, ...this.value } );
  2965. const snippet = this.node.build( builder, output );
  2966. builder.setContext( previousContext );
  2967. return snippet;
  2968. }
  2969. }
  2970. const context = /*@__PURE__*/ nodeProxy( ContextNode );
  2971. const label = ( node, name ) => context( node, { label: name } );
  2972. addMethodChaining( 'context', context );
  2973. addMethodChaining( 'label', label );
  2974. /**
  2975. * Class for representing shader variables as nodes. Variables are create from
  2976. * existing nodes like the following:
  2977. *
  2978. * ```js
  2979. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  2980. * ```
  2981. *
  2982. * @augments Node
  2983. */
  2984. class VarNode extends Node {
  2985. static get type() {
  2986. return 'VarNode';
  2987. }
  2988. /**
  2989. * Constructs a new variable node.
  2990. *
  2991. * @param {Node} node - The node for which a variable should be created.
  2992. * @param {String?} name - The name of the variable in the shader.
  2993. */
  2994. constructor( node, name = null ) {
  2995. super();
  2996. /**
  2997. * The node for which a variable should be created.
  2998. *
  2999. * @type {Node}
  3000. */
  3001. this.node = node;
  3002. /**
  3003. * The name of the variable in the shader. If no name is defined,
  3004. * the node system auto-generates one.
  3005. *
  3006. * @type {String?}
  3007. * @default null
  3008. */
  3009. this.name = name;
  3010. /**
  3011. * `VarNonde` sets this property to `true` by default.
  3012. *
  3013. * @type {Boolean}
  3014. * @default true
  3015. */
  3016. this.global = true;
  3017. /**
  3018. * This flag can be used for type testing.
  3019. *
  3020. * @type {Boolean}
  3021. * @readonly
  3022. * @default true
  3023. */
  3024. this.isVarNode = true;
  3025. }
  3026. getHash( builder ) {
  3027. return this.name || super.getHash( builder );
  3028. }
  3029. getNodeType( builder ) {
  3030. return this.node.getNodeType( builder );
  3031. }
  3032. generate( builder ) {
  3033. const { node, name } = this;
  3034. const nodeVar = builder.getVarFromNode( this, name, builder.getVectorType( this.getNodeType( builder ) ) );
  3035. const propertyName = builder.getPropertyName( nodeVar );
  3036. const snippet = node.build( builder, nodeVar.type );
  3037. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  3038. return propertyName;
  3039. }
  3040. }
  3041. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  3042. addMethodChaining( 'toVar', ( ...params ) => createVar( ...params ).append() );
  3043. // Deprecated
  3044. const temp = ( node ) => { // @deprecated, r170
  3045. console.warn( 'TSL: "temp" is deprecated. Use ".toVar()" instead.' );
  3046. return createVar( node );
  3047. };
  3048. addMethodChaining( 'temp', temp );
  3049. /**
  3050. * Class for representing shader varyings as nodes. Varyings are create from
  3051. * existing nodes like the following:
  3052. *
  3053. * ```js
  3054. * const positionLocal = positionGeometry.varying( 'vPositionLocal' );
  3055. * ```
  3056. *
  3057. * @augments Node
  3058. */
  3059. class VaryingNode extends Node {
  3060. static get type() {
  3061. return 'VaryingNode';
  3062. }
  3063. /**
  3064. * Constructs a new varying node.
  3065. *
  3066. * @param {Node} node - The node for which a varying should be created.
  3067. * @param {String?} name - The name of the varying in the shader.
  3068. */
  3069. constructor( node, name = null ) {
  3070. super();
  3071. /**
  3072. * The node for which a varying should be created.
  3073. *
  3074. * @type {Node}
  3075. */
  3076. this.node = node;
  3077. /**
  3078. * The name of the varying in the shader. If no name is defined,
  3079. * the node system auto-generates one.
  3080. *
  3081. * @type {String?}
  3082. * @default null
  3083. */
  3084. this.name = name;
  3085. /**
  3086. * This flag can be used for type testing.
  3087. *
  3088. * @type {Boolean}
  3089. * @readonly
  3090. * @default true
  3091. */
  3092. this.isVaryingNode = true;
  3093. }
  3094. /**
  3095. * The method is overwritten so it always returns `true`.
  3096. *
  3097. * @return {Boolean} Whether this node is global or not.
  3098. */
  3099. isGlobal() {
  3100. return true;
  3101. }
  3102. getHash( builder ) {
  3103. return this.name || super.getHash( builder );
  3104. }
  3105. getNodeType( builder ) {
  3106. // VaryingNode is auto type
  3107. return this.node.getNodeType( builder );
  3108. }
  3109. /**
  3110. * This method performs the setup of a varying node with the current node builder.
  3111. *
  3112. * @param {NodeBuilder} builder - The current node builder.
  3113. * @return {NodeVarying} The node varying from the node builder.
  3114. */
  3115. setupVarying( builder ) {
  3116. const properties = builder.getNodeProperties( this );
  3117. let varying = properties.varying;
  3118. if ( varying === undefined ) {
  3119. const name = this.name;
  3120. const type = this.getNodeType( builder );
  3121. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  3122. properties.node = this.node;
  3123. }
  3124. // this property can be used to check if the varying can be optimized for a variable
  3125. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  3126. return varying;
  3127. }
  3128. setup( builder ) {
  3129. this.setupVarying( builder );
  3130. }
  3131. analyze( builder ) {
  3132. this.setupVarying( builder );
  3133. return this.node.analyze( builder );
  3134. }
  3135. generate( builder ) {
  3136. const properties = builder.getNodeProperties( this );
  3137. const varying = this.setupVarying( builder );
  3138. if ( properties.propertyName === undefined ) {
  3139. const type = this.getNodeType( builder );
  3140. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  3141. // force node run in vertex stage
  3142. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  3143. properties.propertyName = propertyName;
  3144. }
  3145. return builder.getPropertyName( varying );
  3146. }
  3147. }
  3148. const varying = /*@__PURE__*/ nodeProxy( VaryingNode );
  3149. addMethodChaining( 'varying', varying );
  3150. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  3151. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  3152. const b = color.mul( 0.0773993808 );
  3153. const factor = color.lessThanEqual( 0.04045 );
  3154. const rgbResult = mix( a, b, factor );
  3155. return rgbResult;
  3156. } ).setLayout( {
  3157. name: 'sRGBTransferEOTF',
  3158. type: 'vec3',
  3159. inputs: [
  3160. { name: 'color', type: 'vec3' }
  3161. ]
  3162. } );
  3163. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  3164. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  3165. const b = color.mul( 12.92 );
  3166. const factor = color.lessThanEqual( 0.0031308 );
  3167. const rgbResult = mix( a, b, factor );
  3168. return rgbResult;
  3169. } ).setLayout( {
  3170. name: 'sRGBTransferOETF',
  3171. type: 'vec3',
  3172. inputs: [
  3173. { name: 'color', type: 'vec3' }
  3174. ]
  3175. } );
  3176. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  3177. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  3178. class ColorSpaceNode extends TempNode {
  3179. static get type() {
  3180. return 'ColorSpaceNode';
  3181. }
  3182. constructor( colorNode, source, target ) {
  3183. super( 'vec4' );
  3184. this.colorNode = colorNode;
  3185. this.source = source;
  3186. this.target = target;
  3187. }
  3188. resolveColorSpace( builder, colorSpace ) {
  3189. if ( colorSpace === WORKING_COLOR_SPACE ) {
  3190. return ColorManagement.workingColorSpace;
  3191. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  3192. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  3193. }
  3194. return colorSpace;
  3195. }
  3196. setup( builder ) {
  3197. const { colorNode } = this;
  3198. const source = this.resolveColorSpace( builder, this.source );
  3199. const target = this.resolveColorSpace( builder, this.target );
  3200. let outputNode = colorNode;
  3201. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  3202. return outputNode;
  3203. }
  3204. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  3205. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  3206. }
  3207. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  3208. outputNode = vec4(
  3209. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  3210. outputNode.a
  3211. );
  3212. }
  3213. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  3214. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  3215. }
  3216. return outputNode;
  3217. }
  3218. }
  3219. const toOutputColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, OUTPUT_COLOR_SPACE ) );
  3220. const toWorkingColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), OUTPUT_COLOR_SPACE, WORKING_COLOR_SPACE ) );
  3221. const workingToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, colorSpace ) );
  3222. const colorSpaceToWorking = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), colorSpace, WORKING_COLOR_SPACE ) );
  3223. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  3224. addMethodChaining( 'toOutputColorSpace', toOutputColorSpace );
  3225. addMethodChaining( 'toWorkingColorSpace', toWorkingColorSpace );
  3226. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  3227. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  3228. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  3229. static get type() {
  3230. return 'ReferenceElementNode';
  3231. }
  3232. constructor( referenceNode, indexNode ) {
  3233. super( referenceNode, indexNode );
  3234. this.referenceNode = referenceNode;
  3235. this.isReferenceElementNode = true;
  3236. }
  3237. getNodeType() {
  3238. return this.referenceNode.uniformType;
  3239. }
  3240. generate( builder ) {
  3241. const snippet = super.generate( builder );
  3242. const arrayType = this.referenceNode.getNodeType();
  3243. const elementType = this.getNodeType();
  3244. return builder.format( snippet, arrayType, elementType );
  3245. }
  3246. };
  3247. class ReferenceBaseNode extends Node {
  3248. static get type() {
  3249. return 'ReferenceBaseNode';
  3250. }
  3251. constructor( property, uniformType, object = null, count = null ) {
  3252. super();
  3253. this.property = property;
  3254. this.uniformType = uniformType;
  3255. this.object = object;
  3256. this.count = count;
  3257. this.properties = property.split( '.' );
  3258. this.reference = object;
  3259. this.node = null;
  3260. this.group = null;
  3261. this.updateType = NodeUpdateType.OBJECT;
  3262. }
  3263. setGroup( group ) {
  3264. this.group = group;
  3265. return this;
  3266. }
  3267. element( indexNode ) {
  3268. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  3269. }
  3270. setNodeType( uniformType ) {
  3271. const node = uniform( null, uniformType ).getSelf();
  3272. if ( this.group !== null ) {
  3273. node.setGroup( this.group );
  3274. }
  3275. this.node = node;
  3276. }
  3277. getNodeType( builder ) {
  3278. if ( this.node === null ) {
  3279. this.updateReference( builder );
  3280. this.updateValue();
  3281. }
  3282. return this.node.getNodeType( builder );
  3283. }
  3284. getValueFromReference( object = this.reference ) {
  3285. const { properties } = this;
  3286. let value = object[ properties[ 0 ] ];
  3287. for ( let i = 1; i < properties.length; i ++ ) {
  3288. value = value[ properties[ i ] ];
  3289. }
  3290. return value;
  3291. }
  3292. updateReference( state ) {
  3293. this.reference = this.object !== null ? this.object : state.object;
  3294. return this.reference;
  3295. }
  3296. setup() {
  3297. this.updateValue();
  3298. return this.node;
  3299. }
  3300. update( /*frame*/ ) {
  3301. this.updateValue();
  3302. }
  3303. updateValue() {
  3304. if ( this.node === null ) this.setNodeType( this.uniformType );
  3305. const value = this.getValueFromReference();
  3306. if ( Array.isArray( value ) ) {
  3307. this.node.array = value;
  3308. } else {
  3309. this.node.value = value;
  3310. }
  3311. }
  3312. }
  3313. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  3314. class RendererReferenceNode extends ReferenceBaseNode {
  3315. static get type() {
  3316. return 'RendererReferenceNode';
  3317. }
  3318. constructor( property, inputType, renderer = null ) {
  3319. super( property, inputType, renderer );
  3320. this.renderer = renderer;
  3321. this.setGroup( renderGroup );
  3322. }
  3323. updateReference( state ) {
  3324. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  3325. return this.reference;
  3326. }
  3327. }
  3328. const rendererReference = ( name, type, renderer ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  3329. class ToneMappingNode extends TempNode {
  3330. static get type() {
  3331. return 'ToneMappingNode';
  3332. }
  3333. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  3334. super( 'vec3' );
  3335. this.toneMapping = toneMapping;
  3336. this.exposureNode = exposureNode;
  3337. this.colorNode = colorNode;
  3338. }
  3339. getCacheKey() {
  3340. return hash$1( super.getCacheKey(), this.toneMapping );
  3341. }
  3342. setup( builder ) {
  3343. const colorNode = this.colorNode || builder.context.color;
  3344. const toneMapping = this.toneMapping;
  3345. if ( toneMapping === NoToneMapping ) return colorNode;
  3346. let outputNode = null;
  3347. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  3348. if ( toneMappingFn !== null ) {
  3349. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  3350. } else {
  3351. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  3352. outputNode = colorNode;
  3353. }
  3354. return outputNode;
  3355. }
  3356. }
  3357. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  3358. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  3359. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  3360. class BufferAttributeNode extends InputNode {
  3361. static get type() {
  3362. return 'BufferAttributeNode';
  3363. }
  3364. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  3365. super( value, bufferType );
  3366. this.isBufferNode = true;
  3367. this.bufferType = bufferType;
  3368. this.bufferStride = bufferStride;
  3369. this.bufferOffset = bufferOffset;
  3370. this.usage = StaticDrawUsage;
  3371. this.instanced = false;
  3372. this.attribute = null;
  3373. this.global = true;
  3374. if ( value && value.isBufferAttribute === true ) {
  3375. this.attribute = value;
  3376. this.usage = value.usage;
  3377. this.instanced = value.isInstancedBufferAttribute;
  3378. }
  3379. }
  3380. getHash( builder ) {
  3381. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  3382. let bufferData = builder.globalCache.getData( this.value );
  3383. if ( bufferData === undefined ) {
  3384. bufferData = {
  3385. node: this
  3386. };
  3387. builder.globalCache.setData( this.value, bufferData );
  3388. }
  3389. return bufferData.node.uuid;
  3390. }
  3391. return this.uuid;
  3392. }
  3393. getNodeType( builder ) {
  3394. if ( this.bufferType === null ) {
  3395. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  3396. }
  3397. return this.bufferType;
  3398. }
  3399. setup( builder ) {
  3400. if ( this.attribute !== null ) return;
  3401. const type = this.getNodeType( builder );
  3402. const array = this.value;
  3403. const itemSize = builder.getTypeLength( type );
  3404. const stride = this.bufferStride || itemSize;
  3405. const offset = this.bufferOffset;
  3406. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  3407. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  3408. buffer.setUsage( this.usage );
  3409. this.attribute = bufferAttribute;
  3410. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  3411. }
  3412. generate( builder ) {
  3413. const nodeType = this.getNodeType( builder );
  3414. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  3415. const propertyName = builder.getPropertyName( nodeAttribute );
  3416. let output = null;
  3417. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  3418. this.name = propertyName;
  3419. output = propertyName;
  3420. } else {
  3421. const nodeVarying = varying( this );
  3422. output = nodeVarying.build( builder, nodeType );
  3423. }
  3424. return output;
  3425. }
  3426. getInputType( /*builder*/ ) {
  3427. return 'bufferAttribute';
  3428. }
  3429. setUsage( value ) {
  3430. this.usage = value;
  3431. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  3432. this.attribute.usage = value;
  3433. }
  3434. return this;
  3435. }
  3436. setInstanced( value ) {
  3437. this.instanced = value;
  3438. return this;
  3439. }
  3440. }
  3441. const bufferAttribute = ( array, type, stride, offset ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  3442. const dynamicBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  3443. const instancedBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  3444. const instancedDynamicBufferAttribute = ( array, type, stride, offset ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  3445. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  3446. class ComputeNode extends Node {
  3447. static get type() {
  3448. return 'ComputeNode';
  3449. }
  3450. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  3451. super( 'void' );
  3452. this.isComputeNode = true;
  3453. this.computeNode = computeNode;
  3454. this.count = count;
  3455. this.workgroupSize = workgroupSize;
  3456. this.dispatchCount = 0;
  3457. this.version = 1;
  3458. this.updateBeforeType = NodeUpdateType.OBJECT;
  3459. this.onInitFunction = null;
  3460. this.updateDispatchCount();
  3461. }
  3462. dispose() {
  3463. this.dispatchEvent( { type: 'dispose' } );
  3464. }
  3465. set needsUpdate( value ) {
  3466. if ( value === true ) this.version ++;
  3467. }
  3468. updateDispatchCount() {
  3469. const { count, workgroupSize } = this;
  3470. let size = workgroupSize[ 0 ];
  3471. for ( let i = 1; i < workgroupSize.length; i ++ )
  3472. size *= workgroupSize[ i ];
  3473. this.dispatchCount = Math.ceil( count / size );
  3474. }
  3475. onInit( callback ) {
  3476. this.onInitFunction = callback;
  3477. return this;
  3478. }
  3479. updateBefore( { renderer } ) {
  3480. renderer.compute( this );
  3481. }
  3482. generate( builder ) {
  3483. const { shaderStage } = builder;
  3484. if ( shaderStage === 'compute' ) {
  3485. const snippet = this.computeNode.build( builder, 'void' );
  3486. if ( snippet !== '' ) {
  3487. builder.addLineFlowCode( snippet, this );
  3488. }
  3489. }
  3490. }
  3491. }
  3492. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  3493. addMethodChaining( 'compute', compute );
  3494. /**
  3495. * This node can be used as a cache management component for another node.
  3496. * Caching is in general used by default in {@link NodeBuilder} but this node
  3497. * allows the usage of a shared parent cache during the build process.
  3498. *
  3499. * @augments Node
  3500. */
  3501. class CacheNode extends Node {
  3502. static get type() {
  3503. return 'CacheNode';
  3504. }
  3505. /**
  3506. * Constructs a new cache node.
  3507. *
  3508. * @param {Node} node - The node that should be cached.
  3509. * @param {Boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  3510. */
  3511. constructor( node, parent = true ) {
  3512. super();
  3513. /**
  3514. * The node that should be cached.
  3515. *
  3516. * @type {Node}
  3517. */
  3518. this.node = node;
  3519. /**
  3520. * Whether this node refers to a shared parent cache or not.
  3521. *
  3522. * @type {Boolean}
  3523. * @default true
  3524. */
  3525. this.parent = parent;
  3526. /**
  3527. * This flag can be used for type testing.
  3528. *
  3529. * @type {Boolean}
  3530. * @readonly
  3531. * @default true
  3532. */
  3533. this.isCacheNode = true;
  3534. }
  3535. getNodeType( builder ) {
  3536. return this.node.getNodeType( builder );
  3537. }
  3538. build( builder, ...params ) {
  3539. const previousCache = builder.getCache();
  3540. const cache = builder.getCacheFromNode( this, this.parent );
  3541. builder.setCache( cache );
  3542. const data = this.node.build( builder, ...params );
  3543. builder.setCache( previousCache );
  3544. return data;
  3545. }
  3546. }
  3547. const cache = ( node, ...params ) => nodeObject( new CacheNode( nodeObject( node ), ...params ) );
  3548. addMethodChaining( 'cache', cache );
  3549. /**
  3550. * The class generates the code of a given node but returns another node in the output.
  3551. * This can be used to call a method or node that does not return a value, i.e.
  3552. * type `void` on an input where returning a value is required. Example:
  3553. *
  3554. * ```js
  3555. * material.colorNode = myColor.bypass( runVoidFn() )
  3556. *```
  3557. *
  3558. * @augments Node
  3559. */
  3560. class BypassNode extends Node {
  3561. static get type() {
  3562. return 'BypassNode';
  3563. }
  3564. /**
  3565. * Constructs a new bypass node.
  3566. *
  3567. * @param {Node} outputNode - The output node.
  3568. * @param {Node} callNode - The call node.
  3569. */
  3570. constructor( outputNode, callNode ) {
  3571. super();
  3572. /**
  3573. * This flag can be used for type testing.
  3574. *
  3575. * @type {Boolean}
  3576. * @readonly
  3577. * @default true
  3578. */
  3579. this.isBypassNode = true;
  3580. /**
  3581. * The output node.
  3582. *
  3583. * @type {Node}
  3584. */
  3585. this.outputNode = outputNode;
  3586. /**
  3587. * The call node.
  3588. *
  3589. * @type {Node}
  3590. */
  3591. this.callNode = callNode;
  3592. }
  3593. getNodeType( builder ) {
  3594. return this.outputNode.getNodeType( builder );
  3595. }
  3596. generate( builder ) {
  3597. const snippet = this.callNode.build( builder, 'void' );
  3598. if ( snippet !== '' ) {
  3599. builder.addLineFlowCode( snippet, this );
  3600. }
  3601. return this.outputNode.build( builder );
  3602. }
  3603. }
  3604. const bypass = /*@__PURE__*/ nodeProxy( BypassNode );
  3605. addMethodChaining( 'bypass', bypass );
  3606. class RemapNode extends Node {
  3607. static get type() {
  3608. return 'RemapNode';
  3609. }
  3610. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  3611. super();
  3612. this.node = node;
  3613. this.inLowNode = inLowNode;
  3614. this.inHighNode = inHighNode;
  3615. this.outLowNode = outLowNode;
  3616. this.outHighNode = outHighNode;
  3617. this.doClamp = true;
  3618. }
  3619. setup() {
  3620. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  3621. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  3622. if ( doClamp === true ) t = t.clamp();
  3623. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  3624. }
  3625. }
  3626. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } );
  3627. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode );
  3628. addMethodChaining( 'remap', remap );
  3629. addMethodChaining( 'remapClamp', remapClamp );
  3630. /**
  3631. * This class can be used to implement basic expressions in shader code.
  3632. * Basic examples for that are `return`, `continue` or `discard` statements.
  3633. *
  3634. * @augments Node
  3635. */
  3636. class ExpressionNode extends Node {
  3637. static get type() {
  3638. return 'ExpressionNode';
  3639. }
  3640. /**
  3641. * Constructs a new expression node.
  3642. *
  3643. * @param {String} [snippet=''] - The native code snippet.
  3644. * @param {String} [includes='void'] - The node type.
  3645. */
  3646. constructor( snippet = '', nodeType = 'void' ) {
  3647. super( nodeType );
  3648. /**
  3649. * The native code snippet.
  3650. *
  3651. * @type {String}
  3652. * @default ''
  3653. */
  3654. this.snippet = snippet;
  3655. }
  3656. generate( builder, output ) {
  3657. const type = this.getNodeType( builder );
  3658. const snippet = this.snippet;
  3659. if ( type === 'void' ) {
  3660. builder.addLineFlowCode( snippet, this );
  3661. } else {
  3662. return builder.format( `( ${ snippet } )`, type, output );
  3663. }
  3664. }
  3665. }
  3666. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode );
  3667. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).append();
  3668. const Return = () => expression( 'return' ).append();
  3669. addMethodChaining( 'discard', Discard );
  3670. class RenderOutputNode extends TempNode {
  3671. static get type() {
  3672. return 'RenderOutputNode';
  3673. }
  3674. constructor( colorNode, toneMapping, outputColorSpace ) {
  3675. super( 'vec4' );
  3676. this.colorNode = colorNode;
  3677. this.toneMapping = toneMapping;
  3678. this.outputColorSpace = outputColorSpace;
  3679. this.isRenderOutput = true;
  3680. }
  3681. setup( { context } ) {
  3682. let outputNode = this.colorNode || context.color;
  3683. // tone mapping
  3684. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  3685. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  3686. if ( toneMapping !== NoToneMapping ) {
  3687. outputNode = outputNode.toneMapping( toneMapping );
  3688. }
  3689. // working to output color space
  3690. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  3691. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  3692. }
  3693. return outputNode;
  3694. }
  3695. }
  3696. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  3697. addMethodChaining( 'renderOutput', renderOutput );
  3698. // Non-PURE exports list, side-effects are required here.
  3699. // TSL Base Syntax
  3700. function addNodeElement( name/*, nodeElement*/ ) {
  3701. console.warn( 'THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  3702. }
  3703. /**
  3704. * Base class for representing shader attributes as nodes.
  3705. *
  3706. * @augments Node
  3707. */
  3708. class AttributeNode extends Node {
  3709. static get type() {
  3710. return 'AttributeNode';
  3711. }
  3712. /**
  3713. * Constructs a new attribute node.
  3714. *
  3715. * @param {String} attributeName - The name of the attribute.
  3716. * @param {String?} nodeType - The node type.
  3717. */
  3718. constructor( attributeName, nodeType = null ) {
  3719. super( nodeType );
  3720. /**
  3721. * `AttributeNode` sets this property to `true` by default.
  3722. *
  3723. * @type {Boolean}
  3724. * @default true
  3725. */
  3726. this.global = true;
  3727. this._attributeName = attributeName;
  3728. }
  3729. getHash( builder ) {
  3730. return this.getAttributeName( builder );
  3731. }
  3732. getNodeType( builder ) {
  3733. let nodeType = this.nodeType;
  3734. if ( nodeType === null ) {
  3735. const attributeName = this.getAttributeName( builder );
  3736. if ( builder.hasGeometryAttribute( attributeName ) ) {
  3737. const attribute = builder.geometry.getAttribute( attributeName );
  3738. nodeType = builder.getTypeFromAttribute( attribute );
  3739. } else {
  3740. nodeType = 'float';
  3741. }
  3742. }
  3743. return nodeType;
  3744. }
  3745. /**
  3746. * Sets the attribute name to the given value. The method can be
  3747. * overwritten in derived classes if the final name must be computed
  3748. * analytically.
  3749. *
  3750. * @param {String} attributeName - The name of the attribute.
  3751. * @return {AttributeNode} A reference to this node.
  3752. */
  3753. setAttributeName( attributeName ) {
  3754. this._attributeName = attributeName;
  3755. return this;
  3756. }
  3757. /**
  3758. * Returns the attribute name of this node. The method can be
  3759. * overwritten in derived classes if the final name must be computed
  3760. * analytically.
  3761. *
  3762. * @param {NodeBuilder} builder - The current node builder.
  3763. * @return {String} The attribute name.
  3764. */
  3765. getAttributeName( /*builder*/ ) {
  3766. return this._attributeName;
  3767. }
  3768. generate( builder ) {
  3769. const attributeName = this.getAttributeName( builder );
  3770. const nodeType = this.getNodeType( builder );
  3771. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  3772. if ( geometryAttribute === true ) {
  3773. const attribute = builder.geometry.getAttribute( attributeName );
  3774. const attributeType = builder.getTypeFromAttribute( attribute );
  3775. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  3776. if ( builder.shaderStage === 'vertex' ) {
  3777. return builder.format( nodeAttribute.name, attributeType, nodeType );
  3778. } else {
  3779. const nodeVarying = varying( this );
  3780. return nodeVarying.build( builder, nodeType );
  3781. }
  3782. } else {
  3783. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  3784. return builder.generateConst( nodeType );
  3785. }
  3786. }
  3787. serialize( data ) {
  3788. super.serialize( data );
  3789. data.global = this.global;
  3790. data._attributeName = this._attributeName;
  3791. }
  3792. deserialize( data ) {
  3793. super.deserialize( data );
  3794. this.global = data.global;
  3795. this._attributeName = data._attributeName;
  3796. }
  3797. }
  3798. const attribute = ( name, nodeType ) => nodeObject( new AttributeNode( name, nodeType ) );
  3799. const uv = ( index ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  3800. class TextureSizeNode extends Node {
  3801. static get type() {
  3802. return 'TextureSizeNode';
  3803. }
  3804. constructor( textureNode, levelNode = null ) {
  3805. super( 'uvec2' );
  3806. this.isTextureSizeNode = true;
  3807. this.textureNode = textureNode;
  3808. this.levelNode = levelNode;
  3809. }
  3810. generate( builder, output ) {
  3811. const textureProperty = this.textureNode.build( builder, 'property' );
  3812. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  3813. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  3814. }
  3815. }
  3816. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode );
  3817. class MaxMipLevelNode extends UniformNode {
  3818. static get type() {
  3819. return 'MaxMipLevelNode';
  3820. }
  3821. constructor( textureNode ) {
  3822. super( 0 );
  3823. this._textureNode = textureNode;
  3824. this.updateType = NodeUpdateType.FRAME;
  3825. }
  3826. get textureNode() {
  3827. return this._textureNode;
  3828. }
  3829. get texture() {
  3830. return this._textureNode.value;
  3831. }
  3832. update() {
  3833. const texture = this.texture;
  3834. const images = texture.images;
  3835. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  3836. if ( image && image.width !== undefined ) {
  3837. const { width, height } = image;
  3838. this.value = Math.log2( Math.max( width, height ) );
  3839. }
  3840. }
  3841. }
  3842. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode );
  3843. class TextureNode extends UniformNode {
  3844. static get type() {
  3845. return 'TextureNode';
  3846. }
  3847. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  3848. super( value );
  3849. this.isTextureNode = true;
  3850. this.uvNode = uvNode;
  3851. this.levelNode = levelNode;
  3852. this.biasNode = biasNode;
  3853. this.compareNode = null;
  3854. this.depthNode = null;
  3855. this.gradNode = null;
  3856. this.sampler = true;
  3857. this.updateMatrix = false;
  3858. this.updateType = NodeUpdateType.NONE;
  3859. this.referenceNode = null;
  3860. this._value = value;
  3861. this._matrixUniform = null;
  3862. this.setUpdateMatrix( uvNode === null );
  3863. }
  3864. set value( value ) {
  3865. if ( this.referenceNode ) {
  3866. this.referenceNode.value = value;
  3867. } else {
  3868. this._value = value;
  3869. }
  3870. }
  3871. get value() {
  3872. return this.referenceNode ? this.referenceNode.value : this._value;
  3873. }
  3874. getUniformHash( /*builder*/ ) {
  3875. return this.value.uuid;
  3876. }
  3877. getNodeType( /*builder*/ ) {
  3878. if ( this.value.isDepthTexture === true ) return 'float';
  3879. if ( this.value.type === UnsignedIntType ) {
  3880. return 'uvec4';
  3881. } else if ( this.value.type === IntType ) {
  3882. return 'ivec4';
  3883. }
  3884. return 'vec4';
  3885. }
  3886. getInputType( /*builder*/ ) {
  3887. return 'texture';
  3888. }
  3889. getDefaultUV() {
  3890. return uv( this.value.channel );
  3891. }
  3892. updateReference( /*state*/ ) {
  3893. return this.value;
  3894. }
  3895. getTransformedUV( uvNode ) {
  3896. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  3897. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  3898. }
  3899. setUpdateMatrix( value ) {
  3900. this.updateMatrix = value;
  3901. this.updateType = value ? NodeUpdateType.FRAME : NodeUpdateType.NONE;
  3902. return this;
  3903. }
  3904. setupUV( builder, uvNode ) {
  3905. const texture = this.value;
  3906. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  3907. if ( this.sampler ) {
  3908. uvNode = uvNode.flipY();
  3909. } else {
  3910. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  3911. }
  3912. }
  3913. return uvNode;
  3914. }
  3915. setup( builder ) {
  3916. const properties = builder.getNodeProperties( this );
  3917. properties.referenceNode = this.referenceNode;
  3918. //
  3919. let uvNode = this.uvNode;
  3920. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  3921. uvNode = builder.context.getUV( this );
  3922. }
  3923. if ( ! uvNode ) uvNode = this.getDefaultUV();
  3924. if ( this.updateMatrix === true ) {
  3925. uvNode = this.getTransformedUV( uvNode );
  3926. }
  3927. uvNode = this.setupUV( builder, uvNode );
  3928. //
  3929. let levelNode = this.levelNode;
  3930. if ( levelNode === null && builder.context.getTextureLevel ) {
  3931. levelNode = builder.context.getTextureLevel( this );
  3932. }
  3933. //
  3934. properties.uvNode = uvNode;
  3935. properties.levelNode = levelNode;
  3936. properties.biasNode = this.biasNode;
  3937. properties.compareNode = this.compareNode;
  3938. properties.gradNode = this.gradNode;
  3939. properties.depthNode = this.depthNode;
  3940. }
  3941. generateUV( builder, uvNode ) {
  3942. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  3943. }
  3944. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  3945. const texture = this.value;
  3946. let snippet;
  3947. if ( levelSnippet ) {
  3948. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  3949. } else if ( biasSnippet ) {
  3950. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  3951. } else if ( gradSnippet ) {
  3952. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  3953. } else if ( compareSnippet ) {
  3954. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  3955. } else if ( this.sampler === false ) {
  3956. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  3957. } else {
  3958. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  3959. }
  3960. return snippet;
  3961. }
  3962. generate( builder, output ) {
  3963. const properties = builder.getNodeProperties( this );
  3964. const texture = this.value;
  3965. if ( ! texture || texture.isTexture !== true ) {
  3966. throw new Error( 'TextureNode: Need a three.js texture.' );
  3967. }
  3968. const textureProperty = super.generate( builder, 'property' );
  3969. if ( output === 'sampler' ) {
  3970. return textureProperty + '_sampler';
  3971. } else if ( builder.isReference( output ) ) {
  3972. return textureProperty;
  3973. } else {
  3974. const nodeData = builder.getDataFromNode( this );
  3975. let propertyName = nodeData.propertyName;
  3976. if ( propertyName === undefined ) {
  3977. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  3978. const uvSnippet = this.generateUV( builder, uvNode );
  3979. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  3980. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  3981. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  3982. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  3983. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  3984. const nodeVar = builder.getVarFromNode( this );
  3985. propertyName = builder.getPropertyName( nodeVar );
  3986. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  3987. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  3988. nodeData.snippet = snippet;
  3989. nodeData.propertyName = propertyName;
  3990. }
  3991. let snippet = propertyName;
  3992. const nodeType = this.getNodeType( builder );
  3993. if ( builder.needsToWorkingColorSpace( texture ) ) {
  3994. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  3995. }
  3996. return builder.format( snippet, nodeType, output );
  3997. }
  3998. }
  3999. setSampler( value ) {
  4000. this.sampler = value;
  4001. return this;
  4002. }
  4003. getSampler() {
  4004. return this.sampler;
  4005. }
  4006. // @TODO: Move to TSL
  4007. uv( uvNode ) {
  4008. const textureNode = this.clone();
  4009. textureNode.uvNode = nodeObject( uvNode );
  4010. textureNode.referenceNode = this.getSelf();
  4011. return nodeObject( textureNode );
  4012. }
  4013. blur( amountNode ) {
  4014. const textureNode = this.clone();
  4015. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  4016. textureNode.referenceNode = this.getSelf();
  4017. return nodeObject( textureNode );
  4018. }
  4019. level( levelNode ) {
  4020. const textureNode = this.clone();
  4021. textureNode.levelNode = nodeObject( levelNode );
  4022. textureNode.referenceNode = this.getSelf();
  4023. return nodeObject( textureNode );
  4024. }
  4025. size( levelNode ) {
  4026. return textureSize( this, levelNode );
  4027. }
  4028. bias( biasNode ) {
  4029. const textureNode = this.clone();
  4030. textureNode.biasNode = nodeObject( biasNode );
  4031. textureNode.referenceNode = this.getSelf();
  4032. return nodeObject( textureNode );
  4033. }
  4034. compare( compareNode ) {
  4035. const textureNode = this.clone();
  4036. textureNode.compareNode = nodeObject( compareNode );
  4037. textureNode.referenceNode = this.getSelf();
  4038. return nodeObject( textureNode );
  4039. }
  4040. grad( gradNodeX, gradNodeY ) {
  4041. const textureNode = this.clone();
  4042. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  4043. textureNode.referenceNode = this.getSelf();
  4044. return nodeObject( textureNode );
  4045. }
  4046. depth( depthNode ) {
  4047. const textureNode = this.clone();
  4048. textureNode.depthNode = nodeObject( depthNode );
  4049. textureNode.referenceNode = this.getSelf();
  4050. return nodeObject( textureNode );
  4051. }
  4052. // --
  4053. serialize( data ) {
  4054. super.serialize( data );
  4055. data.value = this.value.toJSON( data.meta ).uuid;
  4056. data.sampler = this.sampler;
  4057. data.updateMatrix = this.updateMatrix;
  4058. data.updateType = this.updateType;
  4059. }
  4060. deserialize( data ) {
  4061. super.deserialize( data );
  4062. this.value = data.meta.textures[ data.value ];
  4063. this.sampler = data.sampler;
  4064. this.updateMatrix = data.updateMatrix;
  4065. this.updateType = data.updateType;
  4066. }
  4067. update() {
  4068. const texture = this.value;
  4069. const matrixUniform = this._matrixUniform;
  4070. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  4071. if ( texture.matrixAutoUpdate === true ) {
  4072. texture.updateMatrix();
  4073. }
  4074. }
  4075. clone() {
  4076. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  4077. newNode.sampler = this.sampler;
  4078. return newNode;
  4079. }
  4080. }
  4081. const texture = /*@__PURE__*/ nodeProxy( TextureNode );
  4082. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  4083. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  4084. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  4085. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  4086. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  4087. const cameraProjectionMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  4088. const cameraProjectionMatrixInverse = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  4089. const cameraViewMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  4090. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  4091. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  4092. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  4093. class Object3DNode extends Node {
  4094. static get type() {
  4095. return 'Object3DNode';
  4096. }
  4097. constructor( scope, object3d = null ) {
  4098. super();
  4099. this.scope = scope;
  4100. this.object3d = object3d;
  4101. this.updateType = NodeUpdateType.OBJECT;
  4102. this._uniformNode = new UniformNode( null );
  4103. }
  4104. getNodeType() {
  4105. const scope = this.scope;
  4106. if ( scope === Object3DNode.WORLD_MATRIX ) {
  4107. return 'mat4';
  4108. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  4109. return 'vec3';
  4110. }
  4111. }
  4112. update( frame ) {
  4113. const object = this.object3d;
  4114. const uniformNode = this._uniformNode;
  4115. const scope = this.scope;
  4116. if ( scope === Object3DNode.WORLD_MATRIX ) {
  4117. uniformNode.value = object.matrixWorld;
  4118. } else if ( scope === Object3DNode.POSITION ) {
  4119. uniformNode.value = uniformNode.value || new Vector3();
  4120. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  4121. } else if ( scope === Object3DNode.SCALE ) {
  4122. uniformNode.value = uniformNode.value || new Vector3();
  4123. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  4124. } else if ( scope === Object3DNode.DIRECTION ) {
  4125. uniformNode.value = uniformNode.value || new Vector3();
  4126. object.getWorldDirection( uniformNode.value );
  4127. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  4128. const camera = frame.camera;
  4129. uniformNode.value = uniformNode.value || new Vector3();
  4130. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  4131. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  4132. }
  4133. }
  4134. generate( builder ) {
  4135. const scope = this.scope;
  4136. if ( scope === Object3DNode.WORLD_MATRIX ) {
  4137. this._uniformNode.nodeType = 'mat4';
  4138. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  4139. this._uniformNode.nodeType = 'vec3';
  4140. }
  4141. return this._uniformNode.build( builder );
  4142. }
  4143. serialize( data ) {
  4144. super.serialize( data );
  4145. data.scope = this.scope;
  4146. }
  4147. deserialize( data ) {
  4148. super.deserialize( data );
  4149. this.scope = data.scope;
  4150. }
  4151. }
  4152. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  4153. Object3DNode.POSITION = 'position';
  4154. Object3DNode.SCALE = 'scale';
  4155. Object3DNode.VIEW_POSITION = 'viewPosition';
  4156. Object3DNode.DIRECTION = 'direction';
  4157. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  4158. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  4159. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION );
  4160. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE );
  4161. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  4162. class ModelNode extends Object3DNode {
  4163. static get type() {
  4164. return 'ModelNode';
  4165. }
  4166. constructor( scope ) {
  4167. super( scope );
  4168. }
  4169. update( frame ) {
  4170. this.object3d = frame.object;
  4171. super.update( frame );
  4172. }
  4173. }
  4174. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  4175. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  4176. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  4177. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  4178. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  4179. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  4180. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  4181. const modelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix ).toVar( 'modelViewMatrix' );
  4182. const highPrecisionModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  4183. builder.context.isHighPrecisionModelViewMatrix = true;
  4184. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  4185. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  4186. } );
  4187. } ).once() )().toVar( 'highPrecisionModelViewMatrix' );
  4188. const highPrecisionModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  4189. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  4190. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  4191. if ( isHighPrecisionModelViewMatrix !== true ) {
  4192. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  4193. }
  4194. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  4195. } );
  4196. } ).once() )().toVar( 'highPrecisionModelNormalMatrix' );
  4197. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  4198. const positionLocal = /*@__PURE__*/ positionGeometry.varying( 'positionLocal' );
  4199. const positionPrevious = /*@__PURE__*/ positionGeometry.varying( 'positionPrevious' );
  4200. const positionWorld = /*@__PURE__*/ modelWorldMatrix.mul( positionLocal ).xyz.varying( 'v_positionWorld' );
  4201. const positionWorldDirection = /*@__PURE__*/ positionLocal.transformDirection( modelWorldMatrix ).varying( 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' );
  4202. const positionView = /*@__PURE__*/ modelViewMatrix.mul( positionLocal ).xyz.varying( 'v_positionView' );
  4203. const positionViewDirection = /*@__PURE__*/ positionView.negate().varying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  4204. class FrontFacingNode extends Node {
  4205. static get type() {
  4206. return 'FrontFacingNode';
  4207. }
  4208. constructor() {
  4209. super( 'bool' );
  4210. this.isFrontFacingNode = true;
  4211. }
  4212. generate( builder ) {
  4213. const { renderer, material } = builder;
  4214. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  4215. if ( material.side === BackSide ) {
  4216. return 'false';
  4217. }
  4218. }
  4219. return builder.getFrontFacing();
  4220. }
  4221. }
  4222. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  4223. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  4224. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  4225. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  4226. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  4227. console.warn( 'TSL.NormalNode: Vertex attribute "normal" not found on geometry.' );
  4228. return vec3( 0, 1, 0 );
  4229. }
  4230. return normalGeometry;
  4231. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  4232. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  4233. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  4234. let node;
  4235. if ( builder.material.flatShading === true ) {
  4236. node = normalFlat;
  4237. } else {
  4238. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  4239. }
  4240. return node;
  4241. }, 'vec3' ).once() )().toVar( 'normalView' );
  4242. const normalWorld = /*@__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  4243. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  4244. return builder.context.setupNormal();
  4245. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedNormalView' );
  4246. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  4247. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  4248. return builder.context.setupClearcoatNormal();
  4249. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedClearcoatNormalView' );
  4250. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  4251. const m = mat3( matrix );
  4252. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  4253. return m.mul( transformedNormal ).xyz;
  4254. } );
  4255. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  4256. const modelNormalViewMatrix = builder.renderer.nodes.modelNormalViewMatrix;
  4257. if ( modelNormalViewMatrix !== null ) {
  4258. return modelNormalViewMatrix.transformDirection( normal );
  4259. }
  4260. //
  4261. const transformedNormal = modelNormalMatrix.mul( normal );
  4262. return cameraViewMatrix.transformDirection( transformedNormal );
  4263. } );
  4264. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onRenderUpdate( ( { material } ) => material.refractionRatio );
  4265. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  4266. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  4267. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  4268. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  4269. class CubeTextureNode extends TextureNode {
  4270. static get type() {
  4271. return 'CubeTextureNode';
  4272. }
  4273. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  4274. super( value, uvNode, levelNode, biasNode );
  4275. this.isCubeTextureNode = true;
  4276. }
  4277. getInputType( /*builder*/ ) {
  4278. return 'cubeTexture';
  4279. }
  4280. getDefaultUV() {
  4281. const texture = this.value;
  4282. if ( texture.mapping === CubeReflectionMapping ) {
  4283. return reflectVector;
  4284. } else if ( texture.mapping === CubeRefractionMapping ) {
  4285. return refractVector;
  4286. } else {
  4287. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  4288. return vec3( 0, 0, 0 );
  4289. }
  4290. }
  4291. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  4292. setupUV( builder, uvNode ) {
  4293. const texture = this.value;
  4294. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  4295. return vec3( uvNode.x.negate(), uvNode.yz );
  4296. } else {
  4297. return uvNode;
  4298. }
  4299. }
  4300. generateUV( builder, cubeUV ) {
  4301. return cubeUV.build( builder, 'vec3' );
  4302. }
  4303. }
  4304. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode );
  4305. class BufferNode extends UniformNode {
  4306. static get type() {
  4307. return 'BufferNode';
  4308. }
  4309. constructor( value, bufferType, bufferCount = 0 ) {
  4310. super( value, bufferType );
  4311. this.isBufferNode = true;
  4312. this.bufferType = bufferType;
  4313. this.bufferCount = bufferCount;
  4314. }
  4315. getElementType( builder ) {
  4316. return this.getNodeType( builder );
  4317. }
  4318. getInputType( /*builder*/ ) {
  4319. return 'buffer';
  4320. }
  4321. }
  4322. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  4323. class UniformArrayElementNode extends ArrayElementNode {
  4324. static get type() {
  4325. return 'UniformArrayElementNode';
  4326. }
  4327. constructor( arrayBuffer, indexNode ) {
  4328. super( arrayBuffer, indexNode );
  4329. this.isArrayBufferElementNode = true;
  4330. }
  4331. generate( builder ) {
  4332. const snippet = super.generate( builder );
  4333. const type = this.getNodeType();
  4334. return builder.format( snippet, 'vec4', type );
  4335. }
  4336. }
  4337. class UniformArrayNode extends BufferNode {
  4338. static get type() {
  4339. return 'UniformArrayNode';
  4340. }
  4341. constructor( value, elementType = null ) {
  4342. super( null, 'vec4' );
  4343. this.array = value;
  4344. this.elementType = elementType;
  4345. this._elementType = null;
  4346. this._elementLength = 0;
  4347. this.updateType = NodeUpdateType.RENDER;
  4348. this.isArrayBufferNode = true;
  4349. }
  4350. getElementType() {
  4351. return this.elementType || this._elementType;
  4352. }
  4353. getElementLength() {
  4354. return this._elementLength;
  4355. }
  4356. update( /*frame*/ ) {
  4357. const { array, value } = this;
  4358. const elementLength = this.getElementLength();
  4359. const elementType = this.getElementType();
  4360. if ( elementLength === 1 ) {
  4361. for ( let i = 0; i < array.length; i ++ ) {
  4362. const index = i * 4;
  4363. value[ index ] = array[ i ];
  4364. }
  4365. } else if ( elementType === 'color' ) {
  4366. for ( let i = 0; i < array.length; i ++ ) {
  4367. const index = i * 4;
  4368. const vector = array[ i ];
  4369. value[ index ] = vector.r;
  4370. value[ index + 1 ] = vector.g;
  4371. value[ index + 2 ] = vector.b || 0;
  4372. //value[ index + 3 ] = vector.a || 0;
  4373. }
  4374. } else {
  4375. for ( let i = 0; i < array.length; i ++ ) {
  4376. const index = i * 4;
  4377. const vector = array[ i ];
  4378. value[ index ] = vector.x;
  4379. value[ index + 1 ] = vector.y;
  4380. value[ index + 2 ] = vector.z || 0;
  4381. value[ index + 3 ] = vector.w || 0;
  4382. }
  4383. }
  4384. }
  4385. setup( builder ) {
  4386. const length = this.array.length;
  4387. this._elementType = this.elementType === null ? getValueType( this.array[ 0 ] ) : this.elementType;
  4388. this._elementLength = builder.getTypeLength( this._elementType );
  4389. let arrayType = Float32Array;
  4390. if ( this._elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  4391. else if ( this._elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  4392. this.value = new arrayType( length * 4 );
  4393. this.bufferCount = length;
  4394. this.bufferType = builder.changeComponentType( 'vec4', builder.getComponentType( this._elementType ) );
  4395. return super.setup( builder );
  4396. }
  4397. element( indexNode ) {
  4398. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  4399. }
  4400. }
  4401. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  4402. //
  4403. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  4404. console.warn( 'TSL.UniformArrayNode: uniforms() has been renamed to uniformArray().' );
  4405. return nodeObject( new UniformArrayNode( values, nodeType ) );
  4406. };
  4407. class ReferenceElementNode extends ArrayElementNode {
  4408. static get type() {
  4409. return 'ReferenceElementNode';
  4410. }
  4411. constructor( referenceNode, indexNode ) {
  4412. super( referenceNode, indexNode );
  4413. this.referenceNode = referenceNode;
  4414. this.isReferenceElementNode = true;
  4415. }
  4416. getNodeType() {
  4417. return this.referenceNode.uniformType;
  4418. }
  4419. generate( builder ) {
  4420. const snippet = super.generate( builder );
  4421. const arrayType = this.referenceNode.getNodeType();
  4422. const elementType = this.getNodeType();
  4423. return builder.format( snippet, arrayType, elementType );
  4424. }
  4425. }
  4426. // TODO: Extends this from ReferenceBaseNode
  4427. class ReferenceNode extends Node {
  4428. static get type() {
  4429. return 'ReferenceNode';
  4430. }
  4431. constructor( property, uniformType, object = null, count = null ) {
  4432. super();
  4433. this.property = property;
  4434. this.uniformType = uniformType;
  4435. this.object = object;
  4436. this.count = count;
  4437. this.properties = property.split( '.' );
  4438. this.reference = object;
  4439. this.node = null;
  4440. this.group = null;
  4441. this.name = null;
  4442. this.updateType = NodeUpdateType.OBJECT;
  4443. }
  4444. element( indexNode ) {
  4445. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  4446. }
  4447. setGroup( group ) {
  4448. this.group = group;
  4449. return this;
  4450. }
  4451. label( name ) {
  4452. this.name = name;
  4453. return this;
  4454. }
  4455. setNodeType( uniformType ) {
  4456. let node = null;
  4457. if ( this.count !== null ) {
  4458. node = buffer( null, uniformType, this.count );
  4459. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  4460. node = uniformArray( null, uniformType );
  4461. } else if ( uniformType === 'texture' ) {
  4462. node = texture( null );
  4463. } else if ( uniformType === 'cubeTexture' ) {
  4464. node = cubeTexture( null );
  4465. } else {
  4466. node = uniform( null, uniformType );
  4467. }
  4468. if ( this.group !== null ) {
  4469. node.setGroup( this.group );
  4470. }
  4471. if ( this.name !== null ) node.label( this.name );
  4472. this.node = node.getSelf();
  4473. }
  4474. getNodeType( builder ) {
  4475. if ( this.node === null ) {
  4476. this.updateReference( builder );
  4477. this.updateValue();
  4478. }
  4479. return this.node.getNodeType( builder );
  4480. }
  4481. getValueFromReference( object = this.reference ) {
  4482. const { properties } = this;
  4483. let value = object[ properties[ 0 ] ];
  4484. for ( let i = 1; i < properties.length; i ++ ) {
  4485. value = value[ properties[ i ] ];
  4486. }
  4487. return value;
  4488. }
  4489. updateReference( state ) {
  4490. this.reference = this.object !== null ? this.object : state.object;
  4491. return this.reference;
  4492. }
  4493. setup() {
  4494. this.updateValue();
  4495. return this.node;
  4496. }
  4497. update( /*frame*/ ) {
  4498. this.updateValue();
  4499. }
  4500. updateValue() {
  4501. if ( this.node === null ) this.setNodeType( this.uniformType );
  4502. const value = this.getValueFromReference();
  4503. if ( Array.isArray( value ) ) {
  4504. this.node.array = value;
  4505. } else {
  4506. this.node.value = value;
  4507. }
  4508. }
  4509. }
  4510. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  4511. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  4512. class MaterialReferenceNode extends ReferenceNode {
  4513. static get type() {
  4514. return 'MaterialReferenceNode';
  4515. }
  4516. constructor( property, inputType, material = null ) {
  4517. super( property, inputType, material );
  4518. this.material = material;
  4519. //this.updateType = NodeUpdateType.RENDER;
  4520. this.isMaterialReferenceNode = true;
  4521. }
  4522. /*setNodeType( node ) {
  4523. super.setNodeType( node );
  4524. this.node.groupNode = renderGroup;
  4525. }*/
  4526. updateReference( state ) {
  4527. this.reference = this.material !== null ? this.material : state.material;
  4528. return this.reference;
  4529. }
  4530. }
  4531. const materialReference = ( name, type, material ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  4532. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  4533. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  4534. builder.geometry.computeTangents();
  4535. }
  4536. return attribute( 'tangent', 'vec4' );
  4537. } )();
  4538. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  4539. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.varying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  4540. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).varying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  4541. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  4542. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  4543. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  4544. const bitangentGeometry = /*@__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  4545. const bitangentLocal = /*@__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  4546. const bitangentView = /*@__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  4547. const bitangentWorld = /*@__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  4548. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  4549. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  4550. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  4551. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  4552. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  4553. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  4554. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  4555. let bentNormal = anisotropyB.cross( positionViewDirection );
  4556. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  4557. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  4558. return bentNormal;
  4559. } )();
  4560. // Normal Mapping Without Precomputed Tangents
  4561. // http://www.thetenthplanet.de/archives/1180
  4562. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  4563. const { eye_pos, surf_norm, mapN, uv } = inputs;
  4564. const q0 = eye_pos.dFdx();
  4565. const q1 = eye_pos.dFdy();
  4566. const st0 = uv.dFdx();
  4567. const st1 = uv.dFdy();
  4568. const N = surf_norm; // normalized
  4569. const q1perp = q1.cross( N );
  4570. const q0perp = N.cross( q0 );
  4571. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  4572. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  4573. const det = T.dot( T ).max( B.dot( B ) );
  4574. const scale = faceDirection.mul( det.inverseSqrt() );
  4575. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  4576. } );
  4577. class NormalMapNode extends TempNode {
  4578. static get type() {
  4579. return 'NormalMapNode';
  4580. }
  4581. constructor( node, scaleNode = null ) {
  4582. super( 'vec3' );
  4583. this.node = node;
  4584. this.scaleNode = scaleNode;
  4585. this.normalMapType = TangentSpaceNormalMap;
  4586. }
  4587. setup( builder ) {
  4588. const { normalMapType, scaleNode } = this;
  4589. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  4590. if ( scaleNode !== null ) {
  4591. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  4592. }
  4593. let outputNode = null;
  4594. if ( normalMapType === ObjectSpaceNormalMap ) {
  4595. outputNode = transformNormalToView( normalMap );
  4596. } else if ( normalMapType === TangentSpaceNormalMap ) {
  4597. const tangent = builder.hasGeometryAttribute( 'tangent' );
  4598. if ( tangent === true ) {
  4599. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  4600. } else {
  4601. outputNode = perturbNormal2Arb( {
  4602. eye_pos: positionView,
  4603. surf_norm: normalView,
  4604. mapN: normalMap,
  4605. uv: uv()
  4606. } );
  4607. }
  4608. }
  4609. return outputNode;
  4610. }
  4611. }
  4612. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode );
  4613. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  4614. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  4615. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  4616. // It's used to preserve the same TextureNode instance
  4617. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  4618. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  4619. return vec2(
  4620. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  4621. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  4622. ).mul( bumpScale );
  4623. } );
  4624. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  4625. const perturbNormalArb = Fn( ( inputs ) => {
  4626. const { surf_pos, surf_norm, dHdxy } = inputs;
  4627. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  4628. const vSigmaX = surf_pos.dFdx().normalize();
  4629. const vSigmaY = surf_pos.dFdy().normalize();
  4630. const vN = surf_norm; // normalized
  4631. const R1 = vSigmaY.cross( vN );
  4632. const R2 = vN.cross( vSigmaX );
  4633. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  4634. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  4635. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  4636. } );
  4637. class BumpMapNode extends TempNode {
  4638. static get type() {
  4639. return 'BumpMapNode';
  4640. }
  4641. constructor( textureNode, scaleNode = null ) {
  4642. super( 'vec3' );
  4643. this.textureNode = textureNode;
  4644. this.scaleNode = scaleNode;
  4645. }
  4646. setup() {
  4647. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  4648. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  4649. return perturbNormalArb( {
  4650. surf_pos: positionView,
  4651. surf_norm: normalView,
  4652. dHdxy
  4653. } );
  4654. }
  4655. }
  4656. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode );
  4657. const _propertyCache = new Map();
  4658. class MaterialNode extends Node {
  4659. static get type() {
  4660. return 'MaterialNode';
  4661. }
  4662. constructor( scope ) {
  4663. super();
  4664. this.scope = scope;
  4665. }
  4666. getCache( property, type ) {
  4667. let node = _propertyCache.get( property );
  4668. if ( node === undefined ) {
  4669. node = materialReference( property, type );
  4670. _propertyCache.set( property, node );
  4671. }
  4672. return node;
  4673. }
  4674. getFloat( property ) {
  4675. return this.getCache( property, 'float' );
  4676. }
  4677. getColor( property ) {
  4678. return this.getCache( property, 'color' );
  4679. }
  4680. getTexture( property ) {
  4681. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  4682. }
  4683. setup( builder ) {
  4684. const material = builder.context.material;
  4685. const scope = this.scope;
  4686. let node = null;
  4687. if ( scope === MaterialNode.COLOR ) {
  4688. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  4689. if ( material.map && material.map.isTexture === true ) {
  4690. node = colorNode.mul( this.getTexture( 'map' ) );
  4691. } else {
  4692. node = colorNode;
  4693. }
  4694. } else if ( scope === MaterialNode.OPACITY ) {
  4695. const opacityNode = this.getFloat( scope );
  4696. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  4697. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  4698. } else {
  4699. node = opacityNode;
  4700. }
  4701. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  4702. if ( material.specularMap && material.specularMap.isTexture === true ) {
  4703. node = this.getTexture( 'specular' ).r;
  4704. } else {
  4705. node = float( 1 );
  4706. }
  4707. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  4708. const specularIntensity = this.getFloat( scope );
  4709. if ( material.specularMap ) {
  4710. node = specularIntensity.mul( this.getTexture( scope ).a );
  4711. } else {
  4712. node = specularIntensity;
  4713. }
  4714. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  4715. const specularColorNode = this.getColor( scope );
  4716. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  4717. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  4718. } else {
  4719. node = specularColorNode;
  4720. }
  4721. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  4722. const roughnessNode = this.getFloat( scope );
  4723. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  4724. node = roughnessNode.mul( this.getTexture( scope ).g );
  4725. } else {
  4726. node = roughnessNode;
  4727. }
  4728. } else if ( scope === MaterialNode.METALNESS ) {
  4729. const metalnessNode = this.getFloat( scope );
  4730. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  4731. node = metalnessNode.mul( this.getTexture( scope ).b );
  4732. } else {
  4733. node = metalnessNode;
  4734. }
  4735. } else if ( scope === MaterialNode.EMISSIVE ) {
  4736. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  4737. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  4738. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  4739. node = emissiveNode.mul( this.getTexture( scope ) );
  4740. } else {
  4741. node = emissiveNode;
  4742. }
  4743. } else if ( scope === MaterialNode.NORMAL ) {
  4744. if ( material.normalMap ) {
  4745. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  4746. node.normalMapType = material.normalMapType;
  4747. } else if ( material.bumpMap ) {
  4748. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  4749. } else {
  4750. node = normalView;
  4751. }
  4752. } else if ( scope === MaterialNode.CLEARCOAT ) {
  4753. const clearcoatNode = this.getFloat( scope );
  4754. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  4755. node = clearcoatNode.mul( this.getTexture( scope ).r );
  4756. } else {
  4757. node = clearcoatNode;
  4758. }
  4759. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  4760. const clearcoatRoughnessNode = this.getFloat( scope );
  4761. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  4762. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  4763. } else {
  4764. node = clearcoatRoughnessNode;
  4765. }
  4766. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  4767. if ( material.clearcoatNormalMap ) {
  4768. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  4769. } else {
  4770. node = normalView;
  4771. }
  4772. } else if ( scope === MaterialNode.SHEEN ) {
  4773. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  4774. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  4775. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  4776. } else {
  4777. node = sheenNode;
  4778. }
  4779. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  4780. const sheenRoughnessNode = this.getFloat( scope );
  4781. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  4782. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  4783. } else {
  4784. node = sheenRoughnessNode;
  4785. }
  4786. node = node.clamp( 0.07, 1.0 );
  4787. } else if ( scope === MaterialNode.ANISOTROPY ) {
  4788. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  4789. const anisotropyPolar = this.getTexture( scope );
  4790. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  4791. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  4792. } else {
  4793. node = materialAnisotropyVector;
  4794. }
  4795. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  4796. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  4797. if ( material.iridescenceThicknessMap ) {
  4798. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  4799. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  4800. } else {
  4801. node = iridescenceThicknessMaximum;
  4802. }
  4803. } else if ( scope === MaterialNode.TRANSMISSION ) {
  4804. const transmissionNode = this.getFloat( scope );
  4805. if ( material.transmissionMap ) {
  4806. node = transmissionNode.mul( this.getTexture( scope ).r );
  4807. } else {
  4808. node = transmissionNode;
  4809. }
  4810. } else if ( scope === MaterialNode.THICKNESS ) {
  4811. const thicknessNode = this.getFloat( scope );
  4812. if ( material.thicknessMap ) {
  4813. node = thicknessNode.mul( this.getTexture( scope ).g );
  4814. } else {
  4815. node = thicknessNode;
  4816. }
  4817. } else if ( scope === MaterialNode.IOR ) {
  4818. node = this.getFloat( scope );
  4819. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  4820. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  4821. } else if ( scope === MaterialNode.AO_MAP ) {
  4822. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  4823. } else {
  4824. const outputType = this.getNodeType( builder );
  4825. node = this.getCache( scope, outputType );
  4826. }
  4827. return node;
  4828. }
  4829. }
  4830. MaterialNode.ALPHA_TEST = 'alphaTest';
  4831. MaterialNode.COLOR = 'color';
  4832. MaterialNode.OPACITY = 'opacity';
  4833. MaterialNode.SHININESS = 'shininess';
  4834. MaterialNode.SPECULAR = 'specular';
  4835. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  4836. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  4837. MaterialNode.SPECULAR_COLOR = 'specularColor';
  4838. MaterialNode.REFLECTIVITY = 'reflectivity';
  4839. MaterialNode.ROUGHNESS = 'roughness';
  4840. MaterialNode.METALNESS = 'metalness';
  4841. MaterialNode.NORMAL = 'normal';
  4842. MaterialNode.CLEARCOAT = 'clearcoat';
  4843. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  4844. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  4845. MaterialNode.EMISSIVE = 'emissive';
  4846. MaterialNode.ROTATION = 'rotation';
  4847. MaterialNode.SHEEN = 'sheen';
  4848. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  4849. MaterialNode.ANISOTROPY = 'anisotropy';
  4850. MaterialNode.IRIDESCENCE = 'iridescence';
  4851. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  4852. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  4853. MaterialNode.IOR = 'ior';
  4854. MaterialNode.TRANSMISSION = 'transmission';
  4855. MaterialNode.THICKNESS = 'thickness';
  4856. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  4857. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  4858. MaterialNode.LINE_SCALE = 'scale';
  4859. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  4860. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  4861. MaterialNode.LINE_WIDTH = 'linewidth';
  4862. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  4863. MaterialNode.POINT_WIDTH = 'pointWidth';
  4864. MaterialNode.DISPERSION = 'dispersion';
  4865. MaterialNode.LIGHT_MAP = 'light';
  4866. MaterialNode.AO_MAP = 'ao';
  4867. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  4868. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  4869. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  4870. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  4871. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  4872. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  4873. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  4874. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  4875. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  4876. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  4877. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  4878. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  4879. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL ).context( { getUV: null } );
  4880. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  4881. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  4882. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL ).context( { getUV: null } );
  4883. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  4884. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  4885. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  4886. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  4887. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  4888. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  4889. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  4890. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  4891. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  4892. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  4893. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  4894. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  4895. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  4896. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  4897. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  4898. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  4899. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  4900. const materialPointWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_WIDTH );
  4901. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  4902. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  4903. const materialAOMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO_MAP );
  4904. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  4905. return frame.material;
  4906. } ).onRenderUpdate( function ( { material } ) {
  4907. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  4908. } );
  4909. class ModelViewProjectionNode extends TempNode {
  4910. static get type() {
  4911. return 'ModelViewProjectionNode';
  4912. }
  4913. constructor( positionNode = null ) {
  4914. super( 'vec4' );
  4915. this.positionNode = positionNode;
  4916. }
  4917. setup( builder ) {
  4918. if ( builder.shaderStage === 'fragment' ) {
  4919. return varying( builder.context.mvp );
  4920. }
  4921. const position = this.positionNode || positionLocal;
  4922. const viewMatrix = builder.renderer.nodes.modelViewMatrix || modelViewMatrix;
  4923. return cameraProjectionMatrix.mul( viewMatrix ).mul( position );
  4924. }
  4925. }
  4926. const modelViewProjection = /*@__PURE__*/ nodeProxy( ModelViewProjectionNode );
  4927. /**
  4928. * This class represents shader indices of different types. The following predefined node
  4929. * objects cover frequent use cases:
  4930. *
  4931. * - `vertexIndex`: The index of a vertex within a mesh.
  4932. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  4933. * - `drawIndex`: The index of a draw call.
  4934. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  4935. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  4936. * - `subgroupIndex`: The index of the subgroup the current compute invocation belongs to.
  4937. *
  4938. * @augments Node
  4939. */
  4940. class IndexNode extends Node {
  4941. static get type() {
  4942. return 'IndexNode';
  4943. }
  4944. /**
  4945. * Constructs a new index node.
  4946. *
  4947. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationSubgroup'|'draw')} value - The scope of the index node.
  4948. */
  4949. constructor( scope ) {
  4950. super( 'uint' );
  4951. /**
  4952. * The scope of the index node.
  4953. *
  4954. * @type {String}
  4955. */
  4956. this.scope = scope;
  4957. /**
  4958. * This flag can be used for type testing.
  4959. *
  4960. * @type {Boolean}
  4961. * @readonly
  4962. * @default true
  4963. */
  4964. this.isIndexNode = true;
  4965. }
  4966. generate( builder ) {
  4967. const nodeType = this.getNodeType( builder );
  4968. const scope = this.scope;
  4969. let propertyName;
  4970. if ( scope === IndexNode.VERTEX ) {
  4971. propertyName = builder.getVertexIndex();
  4972. } else if ( scope === IndexNode.INSTANCE ) {
  4973. propertyName = builder.getInstanceIndex();
  4974. } else if ( scope === IndexNode.DRAW ) {
  4975. propertyName = builder.getDrawIndex();
  4976. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  4977. propertyName = builder.getInvocationLocalIndex();
  4978. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  4979. propertyName = builder.getInvocationSubgroupIndex();
  4980. } else if ( scope === IndexNode.SUBGROUP ) {
  4981. propertyName = builder.getSubgroupIndex();
  4982. } else {
  4983. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  4984. }
  4985. let output;
  4986. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  4987. output = propertyName;
  4988. } else {
  4989. const nodeVarying = varying( this );
  4990. output = nodeVarying.build( builder, nodeType );
  4991. }
  4992. return output;
  4993. }
  4994. }
  4995. IndexNode.VERTEX = 'vertex';
  4996. IndexNode.INSTANCE = 'instance';
  4997. IndexNode.SUBGROUP = 'subgroup';
  4998. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  4999. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  5000. IndexNode.DRAW = 'draw';
  5001. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  5002. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  5003. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  5004. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  5005. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  5006. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  5007. class InstanceNode extends Node {
  5008. static get type() {
  5009. return 'InstanceNode';
  5010. }
  5011. constructor( count, instanceMatrix, instanceColor ) {
  5012. super( 'void' );
  5013. this.count = count;
  5014. this.instanceMatrix = instanceMatrix;
  5015. this.instanceColor = instanceColor;
  5016. this.instanceMatrixNode = null;
  5017. this.instanceColorNode = null;
  5018. this.updateType = NodeUpdateType.FRAME;
  5019. this.buffer = null;
  5020. this.bufferColor = null;
  5021. }
  5022. setup( builder ) {
  5023. const { count, instanceMatrix, instanceColor } = this;
  5024. let { instanceMatrixNode, instanceColorNode } = this;
  5025. if ( instanceMatrixNode === null ) {
  5026. // 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.
  5027. if ( count <= 1000 ) {
  5028. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  5029. } else {
  5030. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  5031. this.buffer = buffer;
  5032. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  5033. const instanceBuffers = [
  5034. // F.Signature -> bufferAttribute( array, type, stride, offset )
  5035. bufferFn( buffer, 'vec4', 16, 0 ),
  5036. bufferFn( buffer, 'vec4', 16, 4 ),
  5037. bufferFn( buffer, 'vec4', 16, 8 ),
  5038. bufferFn( buffer, 'vec4', 16, 12 )
  5039. ];
  5040. instanceMatrixNode = mat4( ...instanceBuffers );
  5041. }
  5042. this.instanceMatrixNode = instanceMatrixNode;
  5043. }
  5044. if ( instanceColor && instanceColorNode === null ) {
  5045. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  5046. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  5047. this.bufferColor = buffer;
  5048. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  5049. this.instanceColorNode = instanceColorNode;
  5050. }
  5051. // POSITION
  5052. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  5053. positionLocal.assign( instancePosition );
  5054. // NORMAL
  5055. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  5056. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  5057. // ASSIGNS
  5058. normalLocal.assign( instanceNormal );
  5059. }
  5060. // COLOR
  5061. if ( this.instanceColorNode !== null ) {
  5062. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  5063. }
  5064. }
  5065. update( /*frame*/ ) {
  5066. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer != null && this.instanceMatrix.version !== this.buffer.version ) {
  5067. this.buffer.version = this.instanceMatrix.version;
  5068. }
  5069. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor != null && this.instanceColor.version !== this.bufferColor.version ) {
  5070. this.bufferColor.version = this.instanceColor.version;
  5071. }
  5072. }
  5073. }
  5074. const instance = /*@__PURE__*/ nodeProxy( InstanceNode );
  5075. class InstancedMeshNode extends InstanceNode {
  5076. static get type() {
  5077. return 'InstancedMeshNode';
  5078. }
  5079. constructor( instanceMesh ) {
  5080. const { count, instanceMatrix, instanceColor } = instanceMesh;
  5081. super( count, instanceMatrix, instanceColor );
  5082. this.instanceMesh = instanceMesh;
  5083. }
  5084. }
  5085. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode );
  5086. class BatchNode extends Node {
  5087. static get type() {
  5088. return 'BatchNode';
  5089. }
  5090. constructor( batchMesh ) {
  5091. super( 'void' );
  5092. this.batchMesh = batchMesh;
  5093. this.batchingIdNode = null;
  5094. }
  5095. setup( builder ) {
  5096. // POSITION
  5097. if ( this.batchingIdNode === null ) {
  5098. if ( builder.getDrawIndex() === null ) {
  5099. this.batchingIdNode = instanceIndex;
  5100. } else {
  5101. this.batchingIdNode = drawIndex;
  5102. }
  5103. }
  5104. const getIndirectIndex = Fn( ( [ id ] ) => {
  5105. const size = textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 );
  5106. const x = int( id ).modInt( int( size ) );
  5107. const y = int( id ).div( int( size ) );
  5108. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  5109. } ).setLayout( {
  5110. name: 'getIndirectIndex',
  5111. type: 'uint',
  5112. inputs: [
  5113. { name: 'id', type: 'int' }
  5114. ]
  5115. } );
  5116. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  5117. const matricesTexture = this.batchMesh._matricesTexture;
  5118. const size = textureSize( textureLoad( matricesTexture ), 0 );
  5119. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  5120. const x = j.modInt( size );
  5121. const y = j.div( int( size ) );
  5122. const batchingMatrix = mat4(
  5123. textureLoad( matricesTexture, ivec2( x, y ) ),
  5124. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  5125. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  5126. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  5127. );
  5128. const colorsTexture = this.batchMesh._colorsTexture;
  5129. if ( colorsTexture !== null ) {
  5130. const getBatchingColor = Fn( ( [ id ] ) => {
  5131. const size = textureSize( textureLoad( colorsTexture ), 0 ).x;
  5132. const j = id;
  5133. const x = j.modInt( size );
  5134. const y = j.div( size );
  5135. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  5136. } ).setLayout( {
  5137. name: 'getBatchingColor',
  5138. type: 'vec3',
  5139. inputs: [
  5140. { name: 'id', type: 'int' }
  5141. ]
  5142. } );
  5143. const color = getBatchingColor( indirectId );
  5144. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  5145. }
  5146. const bm = mat3( batchingMatrix );
  5147. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  5148. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  5149. const batchingNormal = bm.mul( transformedNormal ).xyz;
  5150. normalLocal.assign( batchingNormal );
  5151. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  5152. tangentLocal.mulAssign( bm );
  5153. }
  5154. }
  5155. }
  5156. const batch = /*@__PURE__*/ nodeProxy( BatchNode );
  5157. const _frameId = new WeakMap();
  5158. class SkinningNode extends Node {
  5159. static get type() {
  5160. return 'SkinningNode';
  5161. }
  5162. constructor( skinnedMesh, useReference = false ) {
  5163. super( 'void' );
  5164. this.skinnedMesh = skinnedMesh;
  5165. this.useReference = useReference;
  5166. this.updateType = NodeUpdateType.OBJECT;
  5167. //
  5168. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  5169. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  5170. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  5171. if ( useReference ) {
  5172. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  5173. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  5174. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  5175. } else {
  5176. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  5177. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  5178. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  5179. }
  5180. this.bindMatrixNode = bindMatrixNode;
  5181. this.bindMatrixInverseNode = bindMatrixInverseNode;
  5182. this.boneMatricesNode = boneMatricesNode;
  5183. this.previousBoneMatricesNode = null;
  5184. }
  5185. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = positionLocal ) {
  5186. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  5187. const boneMatX = boneMatrices.element( skinIndexNode.x );
  5188. const boneMatY = boneMatrices.element( skinIndexNode.y );
  5189. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  5190. const boneMatW = boneMatrices.element( skinIndexNode.w );
  5191. // POSITION
  5192. const skinVertex = bindMatrixNode.mul( position );
  5193. const skinned = add(
  5194. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  5195. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  5196. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  5197. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  5198. );
  5199. return bindMatrixInverseNode.mul( skinned ).xyz;
  5200. }
  5201. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  5202. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  5203. const boneMatX = boneMatrices.element( skinIndexNode.x );
  5204. const boneMatY = boneMatrices.element( skinIndexNode.y );
  5205. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  5206. const boneMatW = boneMatrices.element( skinIndexNode.w );
  5207. // NORMAL
  5208. let skinMatrix = add(
  5209. skinWeightNode.x.mul( boneMatX ),
  5210. skinWeightNode.y.mul( boneMatY ),
  5211. skinWeightNode.z.mul( boneMatZ ),
  5212. skinWeightNode.w.mul( boneMatW )
  5213. );
  5214. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  5215. return skinMatrix.transformDirection( normal ).xyz;
  5216. }
  5217. getPreviousSkinnedPosition( builder ) {
  5218. const skinnedMesh = builder.object;
  5219. if ( this.previousBoneMatricesNode === null ) {
  5220. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  5221. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  5222. }
  5223. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  5224. }
  5225. needsPreviousBoneMatrices( builder ) {
  5226. const mrt = builder.renderer.getMRT();
  5227. return mrt && mrt.has( 'velocity' );
  5228. }
  5229. setup( builder ) {
  5230. if ( this.needsPreviousBoneMatrices( builder ) ) {
  5231. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  5232. }
  5233. const skinPosition = this.getSkinnedPosition();
  5234. positionLocal.assign( skinPosition );
  5235. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  5236. const skinNormal = this.getSkinnedNormal();
  5237. normalLocal.assign( skinNormal );
  5238. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  5239. tangentLocal.assign( skinNormal );
  5240. }
  5241. }
  5242. }
  5243. generate( builder, output ) {
  5244. if ( output !== 'void' ) {
  5245. return positionLocal.build( builder, output );
  5246. }
  5247. }
  5248. update( frame ) {
  5249. const object = this.useReference ? frame.object : this.skinnedMesh;
  5250. const skeleton = object.skeleton;
  5251. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  5252. _frameId.set( skeleton, frame.frameId );
  5253. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  5254. skeleton.update();
  5255. }
  5256. }
  5257. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  5258. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  5259. class LoopNode extends Node {
  5260. static get type() {
  5261. return 'LoopNode';
  5262. }
  5263. constructor( params = [] ) {
  5264. super();
  5265. this.params = params;
  5266. }
  5267. getVarName( index ) {
  5268. return String.fromCharCode( 'i'.charCodeAt() + index );
  5269. }
  5270. getProperties( builder ) {
  5271. const properties = builder.getNodeProperties( this );
  5272. if ( properties.stackNode !== undefined ) return properties;
  5273. //
  5274. const inputs = {};
  5275. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  5276. const param = this.params[ i ];
  5277. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  5278. const type = ( param.isNode !== true && param.type ) || 'int';
  5279. inputs[ name ] = expression( name, type );
  5280. }
  5281. const stack = builder.addStack(); // TODO: cache() it
  5282. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  5283. properties.stackNode = stack;
  5284. builder.removeStack();
  5285. return properties;
  5286. }
  5287. getNodeType( builder ) {
  5288. const { returnsNode } = this.getProperties( builder );
  5289. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  5290. }
  5291. setup( builder ) {
  5292. // setup properties
  5293. this.getProperties( builder );
  5294. }
  5295. generate( builder ) {
  5296. const properties = this.getProperties( builder );
  5297. const params = this.params;
  5298. const stackNode = properties.stackNode;
  5299. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  5300. const param = params[ i ];
  5301. let start = null, end = null, name = null, type = null, condition = null, update = null;
  5302. if ( param.isNode ) {
  5303. type = 'int';
  5304. name = this.getVarName( i );
  5305. start = '0';
  5306. end = param.build( builder, type );
  5307. condition = '<';
  5308. } else {
  5309. type = param.type || 'int';
  5310. name = param.name || this.getVarName( i );
  5311. start = param.start;
  5312. end = param.end;
  5313. condition = param.condition;
  5314. update = param.update;
  5315. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  5316. else if ( start && start.isNode ) start = start.build( builder, type );
  5317. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  5318. else if ( end && end.isNode ) end = end.build( builder, type );
  5319. if ( start !== undefined && end === undefined ) {
  5320. start = start + ' - 1';
  5321. end = '0';
  5322. condition = '>=';
  5323. } else if ( end !== undefined && start === undefined ) {
  5324. start = '0';
  5325. condition = '<';
  5326. }
  5327. if ( condition === undefined ) {
  5328. if ( Number( start ) > Number( end ) ) {
  5329. condition = '>=';
  5330. } else {
  5331. condition = '<';
  5332. }
  5333. }
  5334. }
  5335. const internalParam = { start, end, condition };
  5336. //
  5337. const startSnippet = internalParam.start;
  5338. const endSnippet = internalParam.end;
  5339. let declarationSnippet = '';
  5340. let conditionalSnippet = '';
  5341. let updateSnippet = '';
  5342. if ( ! update ) {
  5343. if ( type === 'int' || type === 'uint' ) {
  5344. if ( condition.includes( '<' ) ) update = '++';
  5345. else update = '--';
  5346. } else {
  5347. if ( condition.includes( '<' ) ) update = '+= 1.';
  5348. else update = '-= 1.';
  5349. }
  5350. }
  5351. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  5352. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  5353. updateSnippet += name + ' ' + update;
  5354. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  5355. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  5356. }
  5357. const stackSnippet = stackNode.build( builder, 'void' );
  5358. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  5359. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  5360. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  5361. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  5362. }
  5363. builder.addFlowTab();
  5364. return returnsSnippet;
  5365. }
  5366. }
  5367. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  5368. const Continue = () => expression( 'continue' ).append();
  5369. const Break = () => expression( 'break' ).append();
  5370. //
  5371. const loop = ( ...params ) => { // @deprecated, r168
  5372. console.warn( 'TSL.LoopNode: loop() has been renamed to Loop().' );
  5373. return Loop( ...params );
  5374. };
  5375. const _morphTextures = /*@__PURE__*/ new WeakMap();
  5376. const _morphVec4 = /*@__PURE__*/ new Vector4();
  5377. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  5378. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  5379. const y = texelIndex.div( width );
  5380. const x = texelIndex.sub( y.mul( width ) );
  5381. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  5382. return bufferAttrib.mul( influence );
  5383. } );
  5384. function getEntry( geometry ) {
  5385. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  5386. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  5387. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  5388. // instead of using attributes, the WebGL 2 code path encodes morph targets
  5389. // into an array of data textures. Each layer represents a single morph target.
  5390. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  5391. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  5392. let entry = _morphTextures.get( geometry );
  5393. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  5394. if ( entry !== undefined ) entry.texture.dispose();
  5395. const morphTargets = geometry.morphAttributes.position || [];
  5396. const morphNormals = geometry.morphAttributes.normal || [];
  5397. const morphColors = geometry.morphAttributes.color || [];
  5398. let vertexDataCount = 0;
  5399. if ( hasMorphPosition === true ) vertexDataCount = 1;
  5400. if ( hasMorphNormals === true ) vertexDataCount = 2;
  5401. if ( hasMorphColors === true ) vertexDataCount = 3;
  5402. let width = geometry.attributes.position.count * vertexDataCount;
  5403. let height = 1;
  5404. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  5405. if ( width > maxTextureSize ) {
  5406. height = Math.ceil( width / maxTextureSize );
  5407. width = maxTextureSize;
  5408. }
  5409. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  5410. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  5411. bufferTexture.type = FloatType;
  5412. bufferTexture.needsUpdate = true;
  5413. // fill buffer
  5414. const vertexDataStride = vertexDataCount * 4;
  5415. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  5416. const morphTarget = morphTargets[ i ];
  5417. const morphNormal = morphNormals[ i ];
  5418. const morphColor = morphColors[ i ];
  5419. const offset = width * height * 4 * i;
  5420. for ( let j = 0; j < morphTarget.count; j ++ ) {
  5421. const stride = j * vertexDataStride;
  5422. if ( hasMorphPosition === true ) {
  5423. _morphVec4.fromBufferAttribute( morphTarget, j );
  5424. buffer[ offset + stride + 0 ] = _morphVec4.x;
  5425. buffer[ offset + stride + 1 ] = _morphVec4.y;
  5426. buffer[ offset + stride + 2 ] = _morphVec4.z;
  5427. buffer[ offset + stride + 3 ] = 0;
  5428. }
  5429. if ( hasMorphNormals === true ) {
  5430. _morphVec4.fromBufferAttribute( morphNormal, j );
  5431. buffer[ offset + stride + 4 ] = _morphVec4.x;
  5432. buffer[ offset + stride + 5 ] = _morphVec4.y;
  5433. buffer[ offset + stride + 6 ] = _morphVec4.z;
  5434. buffer[ offset + stride + 7 ] = 0;
  5435. }
  5436. if ( hasMorphColors === true ) {
  5437. _morphVec4.fromBufferAttribute( morphColor, j );
  5438. buffer[ offset + stride + 8 ] = _morphVec4.x;
  5439. buffer[ offset + stride + 9 ] = _morphVec4.y;
  5440. buffer[ offset + stride + 10 ] = _morphVec4.z;
  5441. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  5442. }
  5443. }
  5444. }
  5445. entry = {
  5446. count: morphTargetsCount,
  5447. texture: bufferTexture,
  5448. stride: vertexDataCount,
  5449. size: new Vector2( width, height )
  5450. };
  5451. _morphTextures.set( geometry, entry );
  5452. function disposeTexture() {
  5453. bufferTexture.dispose();
  5454. _morphTextures.delete( geometry );
  5455. geometry.removeEventListener( 'dispose', disposeTexture );
  5456. }
  5457. geometry.addEventListener( 'dispose', disposeTexture );
  5458. }
  5459. return entry;
  5460. }
  5461. class MorphNode extends Node {
  5462. static get type() {
  5463. return 'MorphNode';
  5464. }
  5465. constructor( mesh ) {
  5466. super( 'void' );
  5467. this.mesh = mesh;
  5468. this.morphBaseInfluence = uniform( 1 );
  5469. this.updateType = NodeUpdateType.OBJECT;
  5470. }
  5471. setup( builder ) {
  5472. const { geometry } = builder;
  5473. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  5474. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  5475. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  5476. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  5477. // nodes
  5478. const { texture: bufferMap, stride, size } = getEntry( geometry );
  5479. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  5480. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  5481. const width = int( size.width );
  5482. Loop( morphTargetsCount, ( { i } ) => {
  5483. const influence = float( 0 ).toVar();
  5484. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  5485. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  5486. } else {
  5487. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  5488. }
  5489. if ( hasMorphPosition === true ) {
  5490. positionLocal.addAssign( getMorph( {
  5491. bufferMap,
  5492. influence,
  5493. stride,
  5494. width,
  5495. depth: i,
  5496. offset: int( 0 )
  5497. } ) );
  5498. }
  5499. if ( hasMorphNormals === true ) {
  5500. normalLocal.addAssign( getMorph( {
  5501. bufferMap,
  5502. influence,
  5503. stride,
  5504. width,
  5505. depth: i,
  5506. offset: int( 1 )
  5507. } ) );
  5508. }
  5509. } );
  5510. }
  5511. update() {
  5512. const morphBaseInfluence = this.morphBaseInfluence;
  5513. if ( this.mesh.geometry.morphTargetsRelative ) {
  5514. morphBaseInfluence.value = 1;
  5515. } else {
  5516. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  5517. }
  5518. }
  5519. }
  5520. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode );
  5521. class LightingNode extends Node {
  5522. static get type() {
  5523. return 'LightingNode';
  5524. }
  5525. constructor() {
  5526. super( 'vec3' );
  5527. this.isLightingNode = true;
  5528. }
  5529. generate( /*builder*/ ) {
  5530. console.warn( 'Abstract function.' );
  5531. }
  5532. }
  5533. class AONode extends LightingNode {
  5534. static get type() {
  5535. return 'AONode';
  5536. }
  5537. constructor( aoNode = null ) {
  5538. super();
  5539. this.aoNode = aoNode;
  5540. }
  5541. setup( builder ) {
  5542. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  5543. }
  5544. }
  5545. class LightingContextNode extends ContextNode {
  5546. static get type() {
  5547. return 'LightingContextNode';
  5548. }
  5549. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  5550. super( node );
  5551. this.lightingModel = lightingModel;
  5552. this.backdropNode = backdropNode;
  5553. this.backdropAlphaNode = backdropAlphaNode;
  5554. this._value = null;
  5555. }
  5556. getContext() {
  5557. const { backdropNode, backdropAlphaNode } = this;
  5558. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  5559. directSpecular = vec3().toVar( 'directSpecular' ),
  5560. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  5561. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  5562. const reflectedLight = {
  5563. directDiffuse,
  5564. directSpecular,
  5565. indirectDiffuse,
  5566. indirectSpecular
  5567. };
  5568. const context = {
  5569. radiance: vec3().toVar( 'radiance' ),
  5570. irradiance: vec3().toVar( 'irradiance' ),
  5571. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  5572. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  5573. reflectedLight,
  5574. backdrop: backdropNode,
  5575. backdropAlpha: backdropAlphaNode
  5576. };
  5577. return context;
  5578. }
  5579. setup( builder ) {
  5580. this.value = this._value || ( this._value = this.getContext() );
  5581. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  5582. return super.setup( builder );
  5583. }
  5584. }
  5585. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  5586. class IrradianceNode extends LightingNode {
  5587. static get type() {
  5588. return 'IrradianceNode';
  5589. }
  5590. constructor( node ) {
  5591. super();
  5592. this.node = node;
  5593. }
  5594. setup( builder ) {
  5595. builder.context.irradiance.addAssign( this.node );
  5596. }
  5597. }
  5598. let screenSizeVec, viewportVec;
  5599. class ScreenNode extends Node {
  5600. static get type() {
  5601. return 'ScreenNode';
  5602. }
  5603. constructor( scope ) {
  5604. super();
  5605. this.scope = scope;
  5606. this.isViewportNode = true;
  5607. }
  5608. getNodeType() {
  5609. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  5610. else return 'vec2';
  5611. }
  5612. getUpdateType() {
  5613. let updateType = NodeUpdateType.NONE;
  5614. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  5615. updateType = NodeUpdateType.RENDER;
  5616. }
  5617. this.updateType = updateType;
  5618. return updateType;
  5619. }
  5620. update( { renderer } ) {
  5621. const renderTarget = renderer.getRenderTarget();
  5622. if ( this.scope === ScreenNode.VIEWPORT ) {
  5623. if ( renderTarget !== null ) {
  5624. viewportVec.copy( renderTarget.viewport );
  5625. } else {
  5626. renderer.getViewport( viewportVec );
  5627. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  5628. }
  5629. } else {
  5630. if ( renderTarget !== null ) {
  5631. screenSizeVec.width = renderTarget.width;
  5632. screenSizeVec.height = renderTarget.height;
  5633. } else {
  5634. renderer.getDrawingBufferSize( screenSizeVec );
  5635. }
  5636. }
  5637. }
  5638. setup( /*builder*/ ) {
  5639. const scope = this.scope;
  5640. let output = null;
  5641. if ( scope === ScreenNode.SIZE ) {
  5642. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  5643. } else if ( scope === ScreenNode.VIEWPORT ) {
  5644. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  5645. } else {
  5646. output = vec2( screenCoordinate.div( screenSize ) );
  5647. }
  5648. return output;
  5649. }
  5650. generate( builder ) {
  5651. if ( this.scope === ScreenNode.COORDINATE ) {
  5652. let coord = builder.getFragCoord();
  5653. if ( builder.isFlipY() ) {
  5654. // follow webgpu standards
  5655. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  5656. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  5657. }
  5658. return coord;
  5659. }
  5660. return super.generate( builder );
  5661. }
  5662. }
  5663. ScreenNode.COORDINATE = 'coordinate';
  5664. ScreenNode.VIEWPORT = 'viewport';
  5665. ScreenNode.SIZE = 'size';
  5666. ScreenNode.UV = 'uv';
  5667. // Screen
  5668. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  5669. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  5670. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  5671. // Viewport
  5672. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  5673. const viewportSize = viewport.zw;
  5674. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  5675. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  5676. // Deprecated
  5677. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  5678. console.warn( 'TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  5679. return screenSize;
  5680. }, 'vec2' ).once() )();
  5681. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  5682. console.warn( 'TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  5683. return screenUV;
  5684. }, 'vec2' ).once() )();
  5685. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  5686. console.warn( 'TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  5687. return screenUV.flipY();
  5688. }, 'vec2' ).once() )();
  5689. const _size$4 = /*@__PURE__*/ new Vector2();
  5690. class ViewportTextureNode extends TextureNode {
  5691. static get type() {
  5692. return 'ViewportTextureNode';
  5693. }
  5694. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  5695. if ( framebufferTexture === null ) {
  5696. framebufferTexture = new FramebufferTexture();
  5697. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  5698. }
  5699. super( framebufferTexture, uvNode, levelNode );
  5700. this.generateMipmaps = false;
  5701. this.isOutputTextureNode = true;
  5702. this.updateBeforeType = NodeUpdateType.FRAME;
  5703. }
  5704. updateBefore( frame ) {
  5705. const renderer = frame.renderer;
  5706. renderer.getDrawingBufferSize( _size$4 );
  5707. //
  5708. const framebufferTexture = this.value;
  5709. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  5710. framebufferTexture.image.width = _size$4.width;
  5711. framebufferTexture.image.height = _size$4.height;
  5712. framebufferTexture.needsUpdate = true;
  5713. }
  5714. //
  5715. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  5716. framebufferTexture.generateMipmaps = this.generateMipmaps;
  5717. renderer.copyFramebufferToTexture( framebufferTexture );
  5718. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  5719. }
  5720. clone() {
  5721. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  5722. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  5723. return viewportTextureNode;
  5724. }
  5725. }
  5726. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode );
  5727. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  5728. let sharedDepthbuffer = null;
  5729. class ViewportDepthTextureNode extends ViewportTextureNode {
  5730. static get type() {
  5731. return 'ViewportDepthTextureNode';
  5732. }
  5733. constructor( uvNode = screenUV, levelNode = null ) {
  5734. if ( sharedDepthbuffer === null ) {
  5735. sharedDepthbuffer = new DepthTexture();
  5736. }
  5737. super( uvNode, levelNode, sharedDepthbuffer );
  5738. }
  5739. }
  5740. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode );
  5741. class ViewportDepthNode extends Node {
  5742. static get type() {
  5743. return 'ViewportDepthNode';
  5744. }
  5745. constructor( scope, valueNode = null ) {
  5746. super( 'float' );
  5747. this.scope = scope;
  5748. this.valueNode = valueNode;
  5749. this.isViewportDepthNode = true;
  5750. }
  5751. generate( builder ) {
  5752. const { scope } = this;
  5753. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  5754. return builder.getFragDepth();
  5755. }
  5756. return super.generate( builder );
  5757. }
  5758. setup( { camera } ) {
  5759. const { scope } = this;
  5760. const value = this.valueNode;
  5761. let node = null;
  5762. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  5763. if ( value !== null ) {
  5764. node = depthBase().assign( value );
  5765. }
  5766. } else if ( scope === ViewportDepthNode.DEPTH ) {
  5767. if ( camera.isPerspectiveCamera ) {
  5768. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  5769. } else {
  5770. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  5771. }
  5772. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  5773. if ( value !== null ) {
  5774. if ( camera.isPerspectiveCamera ) {
  5775. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  5776. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  5777. } else {
  5778. node = value;
  5779. }
  5780. } else {
  5781. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  5782. }
  5783. }
  5784. return node;
  5785. }
  5786. }
  5787. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  5788. ViewportDepthNode.DEPTH = 'depth';
  5789. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  5790. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  5791. // -near maps to 0; -far maps to 1
  5792. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  5793. // maps orthographic depth in [ 0, 1 ] to viewZ
  5794. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  5795. // NOTE: https://twitter.com/gonnavis/status/1377183786949959682
  5796. // -near maps to 0; -far maps to 1
  5797. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  5798. // maps perspective depth in [ 0, 1 ] to viewZ
  5799. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  5800. // -near maps to 0; -far maps to 1
  5801. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  5802. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  5803. // The final logarithmic depth formula used here is adapted from one described in an
  5804. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  5805. // which was an improvement upon an earlier formula one described in an
  5806. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  5807. // Ulrich's formula is the following:
  5808. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  5809. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  5810. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  5811. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  5812. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  5813. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  5814. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  5815. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  5816. // be used, and ultimately Ulrich's "near plane" version was chosen.
  5817. // Outerra eventually made another improvement to their original "C-constant" variant,
  5818. // but it still does not incorporate the camera near plane (for this version,
  5819. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  5820. // Here we make 4 changes to Ulrich's formula:
  5821. // 1. Clamp the camera near plane so we don't divide by 0.
  5822. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  5823. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  5824. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  5825. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  5826. // so we do the same here, hence the 'viewZ.negate()' call.
  5827. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  5828. near = near.max( 1e-6 ).toVar();
  5829. const numerator = log2( viewZ.negate().div( near ) );
  5830. const denominator = log2( far.div( near ) );
  5831. return numerator.div( denominator );
  5832. };
  5833. // maps logarithmic depth in [ 0, 1 ] to viewZ
  5834. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  5835. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  5836. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  5837. // a negative viewZ).
  5838. const exponent = depth.mul( log( far.div( near ) ) );
  5839. return float( Math.E ).pow( exponent ).mul( near ).negate();
  5840. };
  5841. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  5842. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  5843. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  5844. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  5845. depth.assign = ( value ) => depthBase( value );
  5846. class BuiltinNode extends Node {
  5847. constructor( name ) {
  5848. super( 'float' );
  5849. this.name = name;
  5850. this.isBuiltinNode = true;
  5851. }
  5852. generate( /* builder */ ) {
  5853. return this.name;
  5854. }
  5855. }
  5856. const builtin = nodeProxy( BuiltinNode );
  5857. class ClippingNode extends Node {
  5858. static get type() {
  5859. return 'ClippingNode';
  5860. }
  5861. constructor( scope = ClippingNode.DEFAULT ) {
  5862. super();
  5863. this.scope = scope;
  5864. }
  5865. setup( builder ) {
  5866. super.setup( builder );
  5867. const clippingContext = builder.clippingContext;
  5868. const { intersectionPlanes, unionPlanes } = clippingContext;
  5869. this.hardwareClipping = builder.material.hardwareClipping;
  5870. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  5871. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  5872. } else if ( this.scope === ClippingNode.HARDWARE ) {
  5873. return this.setupHardwareClipping( unionPlanes, builder );
  5874. } else {
  5875. return this.setupDefault( intersectionPlanes, unionPlanes );
  5876. }
  5877. }
  5878. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  5879. return Fn( () => {
  5880. const distanceToPlane = float().toVar( 'distanceToPlane' );
  5881. const distanceGradient = float().toVar( 'distanceToGradient' );
  5882. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  5883. const numUnionPlanes = unionPlanes.length;
  5884. if ( ! this.hardwareClipping && numUnionPlanes > 0 ) {
  5885. const clippingPlanes = uniformArray( unionPlanes );
  5886. Loop( numUnionPlanes, ( { i } ) => {
  5887. const plane = clippingPlanes.element( i );
  5888. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  5889. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  5890. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  5891. } );
  5892. }
  5893. const numIntersectionPlanes = intersectionPlanes.length;
  5894. if ( numIntersectionPlanes > 0 ) {
  5895. const clippingPlanes = uniformArray( intersectionPlanes );
  5896. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  5897. Loop( numIntersectionPlanes, ( { i } ) => {
  5898. const plane = clippingPlanes.element( i );
  5899. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  5900. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  5901. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  5902. } );
  5903. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  5904. }
  5905. diffuseColor.a.mulAssign( clipOpacity );
  5906. diffuseColor.a.equal( 0.0 ).discard();
  5907. } )();
  5908. }
  5909. setupDefault( intersectionPlanes, unionPlanes ) {
  5910. return Fn( () => {
  5911. const numUnionPlanes = unionPlanes.length;
  5912. if ( ! this.hardwareClipping && numUnionPlanes > 0 ) {
  5913. const clippingPlanes = uniformArray( unionPlanes );
  5914. Loop( numUnionPlanes, ( { i } ) => {
  5915. const plane = clippingPlanes.element( i );
  5916. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  5917. } );
  5918. }
  5919. const numIntersectionPlanes = intersectionPlanes.length;
  5920. if ( numIntersectionPlanes > 0 ) {
  5921. const clippingPlanes = uniformArray( intersectionPlanes );
  5922. const clipped = bool( true ).toVar( 'clipped' );
  5923. Loop( numIntersectionPlanes, ( { i } ) => {
  5924. const plane = clippingPlanes.element( i );
  5925. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  5926. } );
  5927. clipped.discard();
  5928. }
  5929. } )();
  5930. }
  5931. setupHardwareClipping( unionPlanes, builder ) {
  5932. const numUnionPlanes = unionPlanes.length;
  5933. builder.enableHardwareClipping( numUnionPlanes );
  5934. return Fn( () => {
  5935. const clippingPlanes = uniformArray( unionPlanes );
  5936. const hw_clip_distances = builtin( builder.getClipDistance() );
  5937. Loop( numUnionPlanes, ( { i } ) => {
  5938. const plane = clippingPlanes.element( i );
  5939. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  5940. hw_clip_distances.element( i ).assign( distance );
  5941. } );
  5942. } )();
  5943. }
  5944. }
  5945. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  5946. ClippingNode.DEFAULT = 'default';
  5947. ClippingNode.HARDWARE = 'hardware';
  5948. const clipping = () => nodeObject( new ClippingNode() );
  5949. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  5950. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  5951. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  5952. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  5953. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  5954. return fract( mul( 1.0e4, sin( mul( 17.0, value.x ).add( mul( 0.1, value.y ) ) ) ).mul( add( 0.1, abs( sin( mul( 13.0, value.y ).add( value.x ) ) ) ) ) );
  5955. } );
  5956. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  5957. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  5958. } );
  5959. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  5960. // Find the discretized derivatives of our coordinates
  5961. const maxDeriv = max$1(
  5962. length( dFdx( position.xyz ) ),
  5963. length( dFdy( position.xyz ) )
  5964. );
  5965. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  5966. // Find two nearest log-discretized noise scales
  5967. const pixScales = vec2(
  5968. exp2( floor( log2( pixScale ) ) ),
  5969. exp2( ceil( log2( pixScale ) ) )
  5970. );
  5971. // Compute alpha thresholds at our two noise scales
  5972. const alpha = vec2(
  5973. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  5974. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  5975. );
  5976. // Factor to interpolate lerp with
  5977. const lerpFactor = fract( log2( pixScale ) );
  5978. // Interpolate alpha threshold from noise at two scales
  5979. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  5980. // Pass into CDF to compute uniformly distrib threshold
  5981. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  5982. const cases = vec3(
  5983. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  5984. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  5985. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  5986. // Find our final, uniformly distributed alpha threshold (ατ)
  5987. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  5988. // Avoids ατ == 0. Could also do ατ =1-ατ
  5989. return clamp( threshold, 1.0e-6, 1.0 );
  5990. } ).setLayout( {
  5991. name: 'getAlphaHashThreshold',
  5992. type: 'float',
  5993. inputs: [
  5994. { name: 'position', type: 'vec3' }
  5995. ]
  5996. } );
  5997. class NodeMaterial extends Material {
  5998. static get type() {
  5999. return 'NodeMaterial';
  6000. }
  6001. get type() {
  6002. return this.constructor.type;
  6003. }
  6004. set type( _value ) { /* */ }
  6005. constructor() {
  6006. super();
  6007. this.isNodeMaterial = true;
  6008. this.forceSinglePass = false;
  6009. this.fog = true;
  6010. this.lights = false;
  6011. this.hardwareClipping = false;
  6012. this.lightsNode = null;
  6013. this.envNode = null;
  6014. this.aoNode = null;
  6015. this.colorNode = null;
  6016. this.normalNode = null;
  6017. this.opacityNode = null;
  6018. this.backdropNode = null;
  6019. this.backdropAlphaNode = null;
  6020. this.alphaTestNode = null;
  6021. this.positionNode = null;
  6022. this.geometryNode = null;
  6023. this.depthNode = null;
  6024. this.shadowPositionNode = null;
  6025. this.receivedShadowNode = null;
  6026. this.castShadowNode = null;
  6027. this.outputNode = null;
  6028. this.mrtNode = null;
  6029. this.fragmentNode = null;
  6030. this.vertexNode = null;
  6031. }
  6032. customProgramCacheKey() {
  6033. return this.type + getCacheKey$1( this );
  6034. }
  6035. build( builder ) {
  6036. this.setup( builder );
  6037. }
  6038. setupObserver( builder ) {
  6039. return new NodeMaterialObserver( builder );
  6040. }
  6041. setup( builder ) {
  6042. builder.context.setupNormal = () => this.setupNormal( builder );
  6043. const renderer = builder.renderer;
  6044. const renderTarget = renderer.getRenderTarget();
  6045. // < VERTEX STAGE >
  6046. builder.addStack();
  6047. builder.stack.outputNode = this.vertexNode || this.setupPosition( builder );
  6048. if ( this.geometryNode !== null ) {
  6049. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  6050. }
  6051. builder.addFlow( 'vertex', builder.removeStack() );
  6052. // < FRAGMENT STAGE >
  6053. builder.addStack();
  6054. let resultNode;
  6055. const clippingNode = this.setupClipping( builder );
  6056. if ( this.depthWrite === true ) {
  6057. // only write depth if depth buffer is configured
  6058. if ( renderTarget !== null ) {
  6059. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  6060. } else {
  6061. if ( renderer.depth === true ) this.setupDepth( builder );
  6062. }
  6063. }
  6064. if ( this.fragmentNode === null ) {
  6065. this.setupDiffuseColor( builder );
  6066. this.setupVariants( builder );
  6067. const outgoingLightNode = this.setupLighting( builder );
  6068. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  6069. // force unsigned floats - useful for RenderTargets
  6070. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  6071. resultNode = this.setupOutput( builder, basicOutput );
  6072. // OUTPUT NODE
  6073. output.assign( resultNode );
  6074. //
  6075. if ( this.outputNode !== null ) resultNode = this.outputNode;
  6076. // MRT
  6077. if ( renderTarget !== null ) {
  6078. const mrt = renderer.getMRT();
  6079. const materialMRT = this.mrtNode;
  6080. if ( mrt !== null ) {
  6081. resultNode = mrt;
  6082. if ( materialMRT !== null ) {
  6083. resultNode = mrt.merge( materialMRT );
  6084. }
  6085. } else if ( materialMRT !== null ) {
  6086. resultNode = materialMRT;
  6087. }
  6088. }
  6089. } else {
  6090. let fragmentNode = this.fragmentNode;
  6091. if ( fragmentNode.isOutputStructNode !== true ) {
  6092. fragmentNode = vec4( fragmentNode );
  6093. }
  6094. resultNode = this.setupOutput( builder, fragmentNode );
  6095. }
  6096. builder.stack.outputNode = resultNode;
  6097. builder.addFlow( 'fragment', builder.removeStack() );
  6098. // < MONITOR >
  6099. builder.monitor = this.setupObserver( builder );
  6100. }
  6101. setupClipping( builder ) {
  6102. if ( builder.clippingContext === null ) return null;
  6103. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  6104. let result = null;
  6105. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  6106. const samples = builder.renderer.samples;
  6107. if ( this.alphaToCoverage && samples > 1 ) {
  6108. // to be added to flow when the color/alpha value has been determined
  6109. result = clippingAlpha();
  6110. } else {
  6111. builder.stack.add( clipping() );
  6112. }
  6113. }
  6114. return result;
  6115. }
  6116. setupHardwareClipping( builder ) {
  6117. this.hardwareClipping = false;
  6118. if ( builder.clippingContext === null ) return;
  6119. const candidateCount = builder.clippingContext.unionPlanes.length;
  6120. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  6121. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  6122. builder.stack.add( hardwareClipping() );
  6123. this.hardwareClipping = true;
  6124. }
  6125. return;
  6126. }
  6127. setupDepth( builder ) {
  6128. const { renderer, camera } = builder;
  6129. // Depth
  6130. let depthNode = this.depthNode;
  6131. if ( depthNode === null ) {
  6132. const mrt = renderer.getMRT();
  6133. if ( mrt && mrt.has( 'depth' ) ) {
  6134. depthNode = mrt.get( 'depth' );
  6135. } else if ( renderer.logarithmicDepthBuffer === true ) {
  6136. if ( camera.isPerspectiveCamera ) {
  6137. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  6138. } else {
  6139. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  6140. }
  6141. }
  6142. }
  6143. if ( depthNode !== null ) {
  6144. depth.assign( depthNode ).append();
  6145. }
  6146. }
  6147. setupPosition( builder ) {
  6148. const { object } = builder;
  6149. const geometry = object.geometry;
  6150. builder.addStack();
  6151. // Vertex
  6152. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  6153. morphReference( object ).append();
  6154. }
  6155. if ( object.isSkinnedMesh === true ) {
  6156. skinningReference( object ).append();
  6157. }
  6158. if ( this.displacementMap ) {
  6159. const displacementMap = materialReference( 'displacementMap', 'texture' );
  6160. const displacementScale = materialReference( 'displacementScale', 'float' );
  6161. const displacementBias = materialReference( 'displacementBias', 'float' );
  6162. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  6163. }
  6164. if ( object.isBatchedMesh ) {
  6165. batch( object ).append();
  6166. }
  6167. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  6168. instancedMesh( object ).append();
  6169. }
  6170. if ( this.positionNode !== null ) {
  6171. positionLocal.assign( this.positionNode );
  6172. }
  6173. this.setupHardwareClipping( builder );
  6174. const mvp = modelViewProjection();
  6175. builder.context.vertex = builder.removeStack();
  6176. builder.context.mvp = mvp;
  6177. return mvp;
  6178. }
  6179. setupDiffuseColor( { object, geometry } ) {
  6180. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  6181. // VERTEX COLORS
  6182. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  6183. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  6184. }
  6185. // Instanced colors
  6186. if ( object.instanceColor ) {
  6187. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  6188. colorNode = instanceColor.mul( colorNode );
  6189. }
  6190. if ( object.isBatchedMesh && object._colorsTexture ) {
  6191. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  6192. colorNode = batchColor.mul( colorNode );
  6193. }
  6194. // COLOR
  6195. diffuseColor.assign( colorNode );
  6196. // OPACITY
  6197. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  6198. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  6199. // ALPHA TEST
  6200. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  6201. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  6202. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  6203. }
  6204. // ALPHA HASH
  6205. if ( this.alphaHash === true ) {
  6206. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  6207. }
  6208. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  6209. diffuseColor.a.assign( 1.0 );
  6210. }
  6211. }
  6212. setupVariants( /*builder*/ ) {
  6213. // Interface function.
  6214. }
  6215. setupOutgoingLight() {
  6216. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  6217. }
  6218. setupNormal() {
  6219. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  6220. }
  6221. setupEnvironment( /*builder*/ ) {
  6222. let node = null;
  6223. if ( this.envNode ) {
  6224. node = this.envNode;
  6225. } else if ( this.envMap ) {
  6226. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  6227. }
  6228. return node;
  6229. }
  6230. setupLightMap( builder ) {
  6231. let node = null;
  6232. if ( builder.material.lightMap ) {
  6233. node = new IrradianceNode( materialLightMap );
  6234. }
  6235. return node;
  6236. }
  6237. setupLights( builder ) {
  6238. const materialLightsNode = [];
  6239. //
  6240. const envNode = this.setupEnvironment( builder );
  6241. if ( envNode && envNode.isLightingNode ) {
  6242. materialLightsNode.push( envNode );
  6243. }
  6244. const lightMapNode = this.setupLightMap( builder );
  6245. if ( lightMapNode && lightMapNode.isLightingNode ) {
  6246. materialLightsNode.push( lightMapNode );
  6247. }
  6248. if ( this.aoNode !== null || builder.material.aoMap ) {
  6249. const aoNode = this.aoNode !== null ? this.aoNode : materialAOMap;
  6250. materialLightsNode.push( new AONode( aoNode ) );
  6251. }
  6252. let lightsN = this.lightsNode || builder.lightsNode;
  6253. if ( materialLightsNode.length > 0 ) {
  6254. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  6255. }
  6256. return lightsN;
  6257. }
  6258. setupLightingModel( /*builder*/ ) {
  6259. // Interface function.
  6260. }
  6261. setupLighting( builder ) {
  6262. const { material } = builder;
  6263. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  6264. // OUTGOING LIGHT
  6265. const lights = this.lights === true || this.lightsNode !== null;
  6266. const lightsNode = lights ? this.setupLights( builder ) : null;
  6267. let outgoingLightNode = this.setupOutgoingLight( builder );
  6268. if ( lightsNode && lightsNode.getScope().hasLights ) {
  6269. const lightingModel = this.setupLightingModel( builder );
  6270. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  6271. } else if ( backdropNode !== null ) {
  6272. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  6273. }
  6274. // EMISSIVE
  6275. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  6276. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  6277. outgoingLightNode = outgoingLightNode.add( emissive );
  6278. }
  6279. return outgoingLightNode;
  6280. }
  6281. setupOutput( builder, outputNode ) {
  6282. // FOG
  6283. if ( this.fog === true ) {
  6284. const fogNode = builder.fogNode;
  6285. if ( fogNode ) outputNode = vec4( fogNode.mix( outputNode.rgb, fogNode.colorNode ), outputNode.a );
  6286. }
  6287. return outputNode;
  6288. }
  6289. setDefaultValues( material ) {
  6290. // This approach is to reuse the native refreshUniforms*
  6291. // and turn available the use of features like transmission and environment in core
  6292. for ( const property in material ) {
  6293. const value = material[ property ];
  6294. if ( this[ property ] === undefined ) {
  6295. this[ property ] = value;
  6296. if ( value && value.clone ) this[ property ] = value.clone();
  6297. }
  6298. }
  6299. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  6300. for ( const key in descriptors ) {
  6301. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  6302. descriptors[ key ].get !== undefined ) {
  6303. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  6304. }
  6305. }
  6306. }
  6307. toJSON( meta ) {
  6308. const isRoot = ( meta === undefined || typeof meta === 'string' );
  6309. if ( isRoot ) {
  6310. meta = {
  6311. textures: {},
  6312. images: {},
  6313. nodes: {}
  6314. };
  6315. }
  6316. const data = Material.prototype.toJSON.call( this, meta );
  6317. const nodeChildren = getNodeChildren( this );
  6318. data.inputNodes = {};
  6319. for ( const { property, childNode } of nodeChildren ) {
  6320. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  6321. }
  6322. // TODO: Copied from Object3D.toJSON
  6323. function extractFromCache( cache ) {
  6324. const values = [];
  6325. for ( const key in cache ) {
  6326. const data = cache[ key ];
  6327. delete data.metadata;
  6328. values.push( data );
  6329. }
  6330. return values;
  6331. }
  6332. if ( isRoot ) {
  6333. const textures = extractFromCache( meta.textures );
  6334. const images = extractFromCache( meta.images );
  6335. const nodes = extractFromCache( meta.nodes );
  6336. if ( textures.length > 0 ) data.textures = textures;
  6337. if ( images.length > 0 ) data.images = images;
  6338. if ( nodes.length > 0 ) data.nodes = nodes;
  6339. }
  6340. return data;
  6341. }
  6342. copy( source ) {
  6343. this.lightsNode = source.lightsNode;
  6344. this.envNode = source.envNode;
  6345. this.colorNode = source.colorNode;
  6346. this.normalNode = source.normalNode;
  6347. this.opacityNode = source.opacityNode;
  6348. this.backdropNode = source.backdropNode;
  6349. this.backdropAlphaNode = source.backdropAlphaNode;
  6350. this.alphaTestNode = source.alphaTestNode;
  6351. this.positionNode = source.positionNode;
  6352. this.geometryNode = source.geometryNode;
  6353. this.depthNode = source.depthNode;
  6354. this.shadowPositionNode = source.shadowPositionNode;
  6355. this.receivedShadowNode = source.receivedShadowNode;
  6356. this.castShadowNode = source.castShadowNode;
  6357. this.outputNode = source.outputNode;
  6358. this.mrtNode = source.mrtNode;
  6359. this.fragmentNode = source.fragmentNode;
  6360. this.vertexNode = source.vertexNode;
  6361. return super.copy( source );
  6362. }
  6363. }
  6364. const _defaultValues$e = /*@__PURE__*/ new PointsMaterial();
  6365. class InstancedPointsNodeMaterial extends NodeMaterial {
  6366. static get type() {
  6367. return 'InstancedPointsNodeMaterial';
  6368. }
  6369. constructor( params = {} ) {
  6370. super();
  6371. this.lights = false;
  6372. this.useAlphaToCoverage = true;
  6373. this.useColor = params.vertexColors;
  6374. this.pointWidth = 1;
  6375. this.pointColorNode = null;
  6376. this.pointWidthNode = null;
  6377. this.setDefaultValues( _defaultValues$e );
  6378. this.setValues( params );
  6379. }
  6380. setup( builder ) {
  6381. this.setupShaders( builder );
  6382. super.setup( builder );
  6383. }
  6384. setupShaders( { renderer } ) {
  6385. const useAlphaToCoverage = this.alphaToCoverage;
  6386. const useColor = this.useColor;
  6387. this.vertexNode = Fn( () => {
  6388. const instancePosition = attribute( 'instancePosition' ).xyz;
  6389. // camera space
  6390. const mvPos = vec4( modelViewMatrix.mul( vec4( instancePosition, 1.0 ) ) );
  6391. const aspect = viewport.z.div( viewport.w );
  6392. // clip space
  6393. const clipPos = cameraProjectionMatrix.mul( mvPos );
  6394. // offset in ndc space
  6395. const offset = positionGeometry.xy.toVar();
  6396. offset.mulAssign( this.pointWidthNode ? this.pointWidthNode : materialPointWidth );
  6397. offset.assign( offset.div( viewport.z ) );
  6398. offset.y.assign( offset.y.mul( aspect ) );
  6399. // back to clip space
  6400. offset.assign( offset.mul( clipPos.w ) );
  6401. //clipPos.xy += offset;
  6402. clipPos.addAssign( vec4( offset, 0, 0 ) );
  6403. return clipPos;
  6404. } )();
  6405. this.fragmentNode = Fn( () => {
  6406. const alpha = float( 1 ).toVar();
  6407. const len2 = lengthSq( uv().mul( 2 ).sub( 1 ) );
  6408. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  6409. const dlen = float( len2.fwidth() ).toVar();
  6410. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  6411. } else {
  6412. len2.greaterThan( 1.0 ).discard();
  6413. }
  6414. let pointColorNode;
  6415. if ( this.pointColorNode ) {
  6416. pointColorNode = this.pointColorNode;
  6417. } else {
  6418. if ( useColor ) {
  6419. const instanceColor = attribute( 'instanceColor' );
  6420. pointColorNode = instanceColor.mul( materialColor );
  6421. } else {
  6422. pointColorNode = materialColor;
  6423. }
  6424. }
  6425. alpha.mulAssign( materialOpacity );
  6426. return vec4( pointColorNode, alpha );
  6427. } )();
  6428. }
  6429. get alphaToCoverage() {
  6430. return this.useAlphaToCoverage;
  6431. }
  6432. set alphaToCoverage( value ) {
  6433. if ( this.useAlphaToCoverage !== value ) {
  6434. this.useAlphaToCoverage = value;
  6435. this.needsUpdate = true;
  6436. }
  6437. }
  6438. }
  6439. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  6440. class LineBasicNodeMaterial extends NodeMaterial {
  6441. static get type() {
  6442. return 'LineBasicNodeMaterial';
  6443. }
  6444. constructor( parameters ) {
  6445. super();
  6446. this.isLineBasicNodeMaterial = true;
  6447. this.lights = false;
  6448. this.setDefaultValues( _defaultValues$d );
  6449. this.setValues( parameters );
  6450. }
  6451. }
  6452. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  6453. class LineDashedNodeMaterial extends NodeMaterial {
  6454. static get type() {
  6455. return 'LineDashedNodeMaterial';
  6456. }
  6457. constructor( parameters ) {
  6458. super();
  6459. this.isLineDashedNodeMaterial = true;
  6460. this.lights = false;
  6461. this.setDefaultValues( _defaultValues$c );
  6462. this.dashOffset = 0;
  6463. this.offsetNode = null;
  6464. this.dashScaleNode = null;
  6465. this.dashSizeNode = null;
  6466. this.gapSizeNode = null;
  6467. this.setValues( parameters );
  6468. }
  6469. setupVariants() {
  6470. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  6471. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  6472. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  6473. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  6474. dashSize.assign( dashSizeNode );
  6475. gapSize.assign( gapSizeNode );
  6476. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  6477. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  6478. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  6479. }
  6480. }
  6481. let _sharedFramebuffer = null;
  6482. class ViewportSharedTextureNode extends ViewportTextureNode {
  6483. static get type() {
  6484. return 'ViewportSharedTextureNode';
  6485. }
  6486. constructor( uvNode = screenUV, levelNode = null ) {
  6487. if ( _sharedFramebuffer === null ) {
  6488. _sharedFramebuffer = new FramebufferTexture();
  6489. }
  6490. super( uvNode, levelNode, _sharedFramebuffer );
  6491. }
  6492. updateReference() {
  6493. return this;
  6494. }
  6495. }
  6496. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode );
  6497. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  6498. class Line2NodeMaterial extends NodeMaterial {
  6499. static get type() {
  6500. return 'Line2NodeMaterial';
  6501. }
  6502. constructor( params = {} ) {
  6503. super();
  6504. this.lights = false;
  6505. this.setDefaultValues( _defaultValues$b );
  6506. this.useAlphaToCoverage = true;
  6507. this.useColor = params.vertexColors;
  6508. this.useDash = params.dashed;
  6509. this.useWorldUnits = false;
  6510. this.dashOffset = 0;
  6511. this.lineWidth = 1;
  6512. this.lineColorNode = null;
  6513. this.offsetNode = null;
  6514. this.dashScaleNode = null;
  6515. this.dashSizeNode = null;
  6516. this.gapSizeNode = null;
  6517. this.blending = NoBlending;
  6518. this.setValues( params );
  6519. }
  6520. setup( builder ) {
  6521. this.setupShaders( builder );
  6522. super.setup( builder );
  6523. }
  6524. setupShaders( { renderer } ) {
  6525. const useAlphaToCoverage = this.alphaToCoverage;
  6526. const useColor = this.useColor;
  6527. const useDash = this.dashed;
  6528. const useWorldUnits = this.worldUnits;
  6529. const trimSegment = Fn( ( { start, end } ) => {
  6530. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  6531. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  6532. const nearEstimate = b.mul( - 0.5 ).div( a );
  6533. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  6534. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  6535. } ).setLayout( {
  6536. name: 'trimSegment',
  6537. type: 'vec4',
  6538. inputs: [
  6539. { name: 'start', type: 'vec4' },
  6540. { name: 'end', type: 'vec4' }
  6541. ]
  6542. } );
  6543. this.vertexNode = Fn( () => {
  6544. const instanceStart = attribute( 'instanceStart' );
  6545. const instanceEnd = attribute( 'instanceEnd' );
  6546. // camera space
  6547. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  6548. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  6549. if ( useDash ) {
  6550. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  6551. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  6552. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  6553. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  6554. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  6555. lineDistance = lineDistance.add( offsetNode );
  6556. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  6557. }
  6558. if ( useWorldUnits ) {
  6559. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  6560. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  6561. }
  6562. const aspect = viewport.z.div( viewport.w );
  6563. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  6564. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  6565. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  6566. // perhaps there is a more elegant solution -- WestLangley
  6567. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  6568. If( perspective, () => {
  6569. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  6570. end.assign( trimSegment( { start: start, end: end } ) );
  6571. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  6572. start.assign( trimSegment( { start: end, end: start } ) );
  6573. } );
  6574. } );
  6575. // clip space
  6576. const clipStart = cameraProjectionMatrix.mul( start );
  6577. const clipEnd = cameraProjectionMatrix.mul( end );
  6578. // ndc space
  6579. const ndcStart = clipStart.xyz.div( clipStart.w );
  6580. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  6581. // direction
  6582. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  6583. // account for clip-space aspect ratio
  6584. dir.x.assign( dir.x.mul( aspect ) );
  6585. dir.assign( dir.normalize() );
  6586. const clip = vec4().toVar();
  6587. if ( useWorldUnits ) {
  6588. // get the offset direction as perpendicular to the view vector
  6589. const worldDir = end.xyz.sub( start.xyz ).normalize();
  6590. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  6591. const worldUp = worldDir.cross( tmpFwd ).normalize();
  6592. const worldFwd = worldDir.cross( worldUp );
  6593. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  6594. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  6595. // height offset
  6596. const hw = materialLineWidth.mul( 0.5 );
  6597. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  6598. // don't extend the line if we're rendering dashes because we
  6599. // won't be rendering the endcaps
  6600. if ( ! useDash ) {
  6601. // cap extension
  6602. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  6603. // add width to the box
  6604. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  6605. // endcaps
  6606. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  6607. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  6608. } );
  6609. }
  6610. // project the worldpos
  6611. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  6612. // shift the depth of the projected points so the line
  6613. // segments overlap neatly
  6614. const clipPose = vec3().toVar();
  6615. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  6616. clip.z.assign( clipPose.z.mul( clip.w ) );
  6617. } else {
  6618. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  6619. // undo aspect ratio adjustment
  6620. dir.x.assign( dir.x.div( aspect ) );
  6621. offset.x.assign( offset.x.div( aspect ) );
  6622. // sign flip
  6623. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  6624. // endcaps
  6625. If( positionGeometry.y.lessThan( 0.0 ), () => {
  6626. offset.assign( offset.sub( dir ) );
  6627. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  6628. offset.assign( offset.add( dir ) );
  6629. } );
  6630. // adjust for linewidth
  6631. offset.assign( offset.mul( materialLineWidth ) );
  6632. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  6633. offset.assign( offset.div( viewport.w ) );
  6634. // select end
  6635. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  6636. // back to clip space
  6637. offset.assign( offset.mul( clip.w ) );
  6638. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  6639. }
  6640. return clip;
  6641. } )();
  6642. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  6643. const p13 = p1.sub( p3 );
  6644. const p43 = p4.sub( p3 );
  6645. const p21 = p2.sub( p1 );
  6646. const d1343 = p13.dot( p43 );
  6647. const d4321 = p43.dot( p21 );
  6648. const d1321 = p13.dot( p21 );
  6649. const d4343 = p43.dot( p43 );
  6650. const d2121 = p21.dot( p21 );
  6651. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  6652. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  6653. const mua = numer.div( denom ).clamp();
  6654. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  6655. return vec2( mua, mub );
  6656. } );
  6657. this.colorNode = Fn( () => {
  6658. const vUv = uv();
  6659. if ( useDash ) {
  6660. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  6661. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  6662. dashSize.assign( dashSizeNode );
  6663. gapSize.assign( gapSizeNode );
  6664. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  6665. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  6666. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  6667. }
  6668. const alpha = float( 1 ).toVar( 'alpha' );
  6669. if ( useWorldUnits ) {
  6670. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  6671. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  6672. // Find the closest points on the view ray and the line segment
  6673. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  6674. const lineDir = worldEnd.sub( worldStart );
  6675. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  6676. const p1 = worldStart.add( lineDir.mul( params.x ) );
  6677. const p2 = rayEnd.mul( params.y );
  6678. const delta = p1.sub( p2 );
  6679. const len = delta.length();
  6680. const norm = len.div( materialLineWidth );
  6681. if ( ! useDash ) {
  6682. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  6683. const dnorm = norm.fwidth();
  6684. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  6685. } else {
  6686. norm.greaterThan( 0.5 ).discard();
  6687. }
  6688. }
  6689. } else {
  6690. // round endcaps
  6691. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  6692. const a = vUv.x;
  6693. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  6694. const len2 = a.mul( a ).add( b.mul( b ) );
  6695. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  6696. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  6697. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  6698. } );
  6699. } else {
  6700. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  6701. const a = vUv.x;
  6702. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  6703. const len2 = a.mul( a ).add( b.mul( b ) );
  6704. len2.greaterThan( 1.0 ).discard();
  6705. } );
  6706. }
  6707. }
  6708. let lineColorNode;
  6709. if ( this.lineColorNode ) {
  6710. lineColorNode = this.lineColorNode;
  6711. } else {
  6712. if ( useColor ) {
  6713. const instanceColorStart = attribute( 'instanceColorStart' );
  6714. const instanceColorEnd = attribute( 'instanceColorEnd' );
  6715. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  6716. lineColorNode = instanceColor.mul( materialColor );
  6717. } else {
  6718. lineColorNode = materialColor;
  6719. }
  6720. }
  6721. return vec4( lineColorNode, alpha );
  6722. } )();
  6723. if ( this.transparent ) {
  6724. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  6725. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  6726. }
  6727. }
  6728. get worldUnits() {
  6729. return this.useWorldUnits;
  6730. }
  6731. set worldUnits( value ) {
  6732. if ( this.useWorldUnits !== value ) {
  6733. this.useWorldUnits = value;
  6734. this.needsUpdate = true;
  6735. }
  6736. }
  6737. get dashed() {
  6738. return this.useDash;
  6739. }
  6740. set dashed( value ) {
  6741. if ( this.useDash !== value ) {
  6742. this.useDash = value;
  6743. this.needsUpdate = true;
  6744. }
  6745. }
  6746. get alphaToCoverage() {
  6747. return this.useAlphaToCoverage;
  6748. }
  6749. set alphaToCoverage( value ) {
  6750. if ( this.useAlphaToCoverage !== value ) {
  6751. this.useAlphaToCoverage = value;
  6752. this.needsUpdate = true;
  6753. }
  6754. }
  6755. }
  6756. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  6757. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  6758. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  6759. class MeshNormalNodeMaterial extends NodeMaterial {
  6760. static get type() {
  6761. return 'MeshNormalNodeMaterial';
  6762. }
  6763. constructor( parameters ) {
  6764. super();
  6765. this.lights = false;
  6766. this.isMeshNormalNodeMaterial = true;
  6767. this.setDefaultValues( _defaultValues$a );
  6768. this.setValues( parameters );
  6769. }
  6770. setupDiffuseColor() {
  6771. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  6772. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  6773. }
  6774. }
  6775. class EquirectUVNode extends TempNode {
  6776. static get type() {
  6777. return 'EquirectUVNode';
  6778. }
  6779. constructor( dirNode = positionWorldDirection ) {
  6780. super( 'vec2' );
  6781. this.dirNode = dirNode;
  6782. }
  6783. setup() {
  6784. const dir = this.dirNode;
  6785. const u = dir.z.atan2( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  6786. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  6787. return vec2( u, v );
  6788. }
  6789. }
  6790. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode );
  6791. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  6792. class CubeRenderTarget extends WebGLCubeRenderTarget {
  6793. constructor( size = 1, options = {} ) {
  6794. super( size, options );
  6795. this.isCubeRenderTarget = true;
  6796. }
  6797. fromEquirectangularTexture( renderer, texture$1 ) {
  6798. const currentMinFilter = texture$1.minFilter;
  6799. const currentGenerateMipmaps = texture$1.generateMipmaps;
  6800. texture$1.generateMipmaps = true;
  6801. this.texture.type = texture$1.type;
  6802. this.texture.colorSpace = texture$1.colorSpace;
  6803. this.texture.generateMipmaps = texture$1.generateMipmaps;
  6804. this.texture.minFilter = texture$1.minFilter;
  6805. this.texture.magFilter = texture$1.magFilter;
  6806. const geometry = new BoxGeometry( 5, 5, 5 );
  6807. const uvNode = equirectUV( positionWorldDirection );
  6808. const material = new NodeMaterial();
  6809. material.colorNode = texture( texture$1, uvNode, 0 );
  6810. material.side = BackSide;
  6811. material.blending = NoBlending;
  6812. const mesh = new Mesh( geometry, material );
  6813. const scene = new Scene();
  6814. scene.add( mesh );
  6815. // Avoid blurred poles
  6816. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  6817. const camera = new CubeCamera( 1, 10, this );
  6818. const currentMRT = renderer.getMRT();
  6819. renderer.setMRT( null );
  6820. camera.update( renderer, scene );
  6821. renderer.setMRT( currentMRT );
  6822. texture$1.minFilter = currentMinFilter;
  6823. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  6824. mesh.geometry.dispose();
  6825. mesh.material.dispose();
  6826. return this;
  6827. }
  6828. }
  6829. const _cache$1 = new WeakMap();
  6830. class CubeMapNode extends TempNode {
  6831. static get type() {
  6832. return 'CubeMapNode';
  6833. }
  6834. constructor( envNode ) {
  6835. super( 'vec3' );
  6836. this.envNode = envNode;
  6837. this._cubeTexture = null;
  6838. this._cubeTextureNode = cubeTexture();
  6839. const defaultTexture = new CubeTexture();
  6840. defaultTexture.isRenderTargetTexture = true;
  6841. this._defaultTexture = defaultTexture;
  6842. this.updateBeforeType = NodeUpdateType.RENDER;
  6843. }
  6844. updateBefore( frame ) {
  6845. const { renderer, material } = frame;
  6846. const envNode = this.envNode;
  6847. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  6848. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  6849. if ( texture && texture.isTexture ) {
  6850. const mapping = texture.mapping;
  6851. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  6852. // check for converted cubemap map
  6853. if ( _cache$1.has( texture ) ) {
  6854. const cubeMap = _cache$1.get( texture );
  6855. mapTextureMapping( cubeMap, texture.mapping );
  6856. this._cubeTexture = cubeMap;
  6857. } else {
  6858. // create cube map from equirectangular map
  6859. const image = texture.image;
  6860. if ( isEquirectangularMapReady$1( image ) ) {
  6861. const renderTarget = new CubeRenderTarget( image.height );
  6862. renderTarget.fromEquirectangularTexture( renderer, texture );
  6863. mapTextureMapping( renderTarget.texture, texture.mapping );
  6864. this._cubeTexture = renderTarget.texture;
  6865. _cache$1.set( texture, renderTarget.texture );
  6866. texture.addEventListener( 'dispose', onTextureDispose );
  6867. } else {
  6868. // default cube texture as fallback when equirectangular texture is not yet loaded
  6869. this._cubeTexture = this._defaultTexture;
  6870. }
  6871. }
  6872. //
  6873. this._cubeTextureNode.value = this._cubeTexture;
  6874. } else {
  6875. // envNode already refers to a cube map
  6876. this._cubeTextureNode = this.envNode;
  6877. }
  6878. }
  6879. }
  6880. }
  6881. setup( builder ) {
  6882. this.updateBefore( builder );
  6883. return this._cubeTextureNode;
  6884. }
  6885. }
  6886. function isEquirectangularMapReady$1( image ) {
  6887. if ( image === null || image === undefined ) return false;
  6888. return image.height > 0;
  6889. }
  6890. function onTextureDispose( event ) {
  6891. const texture = event.target;
  6892. texture.removeEventListener( 'dispose', onTextureDispose );
  6893. const renderTarget = _cache$1.get( texture );
  6894. if ( renderTarget !== undefined ) {
  6895. _cache$1.delete( texture );
  6896. renderTarget.dispose();
  6897. }
  6898. }
  6899. function mapTextureMapping( texture, mapping ) {
  6900. if ( mapping === EquirectangularReflectionMapping ) {
  6901. texture.mapping = CubeReflectionMapping;
  6902. } else if ( mapping === EquirectangularRefractionMapping ) {
  6903. texture.mapping = CubeRefractionMapping;
  6904. }
  6905. }
  6906. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode );
  6907. class BasicEnvironmentNode extends LightingNode {
  6908. static get type() {
  6909. return 'BasicEnvironmentNode';
  6910. }
  6911. constructor( envNode = null ) {
  6912. super();
  6913. this.envNode = envNode;
  6914. }
  6915. setup( builder ) {
  6916. // environment property is used in the finish() method of BasicLightingModel
  6917. builder.context.environment = cubeMapNode( this.envNode );
  6918. }
  6919. }
  6920. class BasicLightMapNode extends LightingNode {
  6921. static get type() {
  6922. return 'BasicLightMapNode';
  6923. }
  6924. constructor( lightMapNode = null ) {
  6925. super();
  6926. this.lightMapNode = lightMapNode;
  6927. }
  6928. setup( builder ) {
  6929. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  6930. const RECIPROCAL_PI = float( 1 / Math.PI );
  6931. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  6932. }
  6933. }
  6934. /**
  6935. * Abstract class for implementing lighting models. The module defines
  6936. * multiple methods that concrete lighting models can implement. These
  6937. * methods are executed at different points during the light evaluation
  6938. * process.
  6939. */
  6940. class LightingModel {
  6941. /**
  6942. * This method is intended for setting up lighting model and context data
  6943. * which are later used in the evaluation process.
  6944. *
  6945. * @param {ContextNode} input - The current node context.
  6946. * @param {StackNode} stack - The current stack.
  6947. * @param {NodeBuilder} builder - The current node builder.
  6948. */
  6949. start( /*input, stack, builder*/ ) { }
  6950. /**
  6951. * This method is intended for executing final tasks like final updates
  6952. * to the outgoing light.
  6953. *
  6954. * @param {ContextNode} input - The current node context.
  6955. * @param {StackNode} stack - The current stack.
  6956. * @param {NodeBuilder} builder - The current node builder.
  6957. */
  6958. finish( /*input, stack, builder*/ ) { }
  6959. /**
  6960. * This method is intended for implementing the direct light term and
  6961. * executed during the build process of directional, point and spot light nodes.
  6962. *
  6963. * @param {Object} input - The input data.
  6964. * @param {StackNode} stack - The current stack.
  6965. * @param {NodeBuilder} builder - The current node builder.
  6966. */
  6967. direct( /*input, stack, builder*/ ) { }
  6968. /**
  6969. * This method is intended for implementing the direct light term for
  6970. * rect area light nodes.
  6971. *
  6972. * @param {Object} input - The input data.
  6973. * @param {StackNode} stack - The current stack.
  6974. * @param {NodeBuilder} builder - The current node builder.
  6975. */
  6976. directRectArea( /*input, stack, builder*/ ) {}
  6977. /**
  6978. * This method is intended for implementing the indirect light term.
  6979. *
  6980. * @param {ContextNode} input - The current node context.
  6981. * @param {StackNode} stack - The current stack.
  6982. * @param {NodeBuilder} builder - The current node builder.
  6983. */
  6984. indirect( /*input, stack, builder*/ ) { }
  6985. /**
  6986. * This method is intended for implementing the ambient occlusion term.
  6987. * Unlike other methods, this method must be called manually by the lighting
  6988. * model in its indirect term.
  6989. *
  6990. * @param {ContextNode} input - The current node context.
  6991. * @param {StackNode} stack - The current stack.
  6992. * @param {NodeBuilder} builder - The current node builder.
  6993. */
  6994. ambientOcclusion( /*input, stack, builder*/ ) { }
  6995. }
  6996. class BasicLightingModel extends LightingModel {
  6997. constructor() {
  6998. super();
  6999. }
  7000. indirect( context, stack, builder ) {
  7001. const ambientOcclusion = context.ambientOcclusion;
  7002. const reflectedLight = context.reflectedLight;
  7003. const irradianceLightMap = builder.context.irradianceLightMap;
  7004. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  7005. // accumulation (baked indirect lighting only)
  7006. if ( irradianceLightMap ) {
  7007. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  7008. } else {
  7009. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  7010. }
  7011. // modulation
  7012. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  7013. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  7014. }
  7015. finish( context, stack, builder ) {
  7016. const material = builder.material;
  7017. const outgoingLight = context.outgoingLight;
  7018. const envNode = builder.context.environment;
  7019. if ( envNode ) {
  7020. switch ( material.combine ) {
  7021. case MultiplyOperation:
  7022. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  7023. break;
  7024. case MixOperation:
  7025. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  7026. break;
  7027. case AddOperation:
  7028. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  7029. break;
  7030. default:
  7031. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  7032. break;
  7033. }
  7034. }
  7035. }
  7036. }
  7037. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  7038. class MeshBasicNodeMaterial extends NodeMaterial {
  7039. static get type() {
  7040. return 'MeshBasicNodeMaterial';
  7041. }
  7042. constructor( parameters ) {
  7043. super();
  7044. this.isMeshBasicNodeMaterial = true;
  7045. this.lights = true;
  7046. this.setDefaultValues( _defaultValues$9 );
  7047. this.setValues( parameters );
  7048. }
  7049. setupNormal() {
  7050. return normalView; // see #28839
  7051. }
  7052. setupEnvironment( builder ) {
  7053. const envNode = super.setupEnvironment( builder );
  7054. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  7055. }
  7056. setupLightMap( builder ) {
  7057. let node = null;
  7058. if ( builder.material.lightMap ) {
  7059. node = new BasicLightMapNode( materialLightMap );
  7060. }
  7061. return node;
  7062. }
  7063. setupOutgoingLight() {
  7064. return diffuseColor.rgb;
  7065. }
  7066. setupLightingModel() {
  7067. return new BasicLightingModel();
  7068. }
  7069. }
  7070. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  7071. // Original approximation by Christophe Schlick '94
  7072. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  7073. // Optimized variant (presented by Epic at SIGGRAPH '13)
  7074. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  7075. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  7076. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  7077. } ); // validated
  7078. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  7079. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  7080. } ); // validated
  7081. const G_BlinnPhong_Implicit = () => float( 0.25 );
  7082. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  7083. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  7084. } );
  7085. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  7086. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  7087. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  7088. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  7089. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  7090. const G = G_BlinnPhong_Implicit();
  7091. const D = D_BlinnPhong( { dotNH } );
  7092. return F.mul( G ).mul( D );
  7093. } );
  7094. class PhongLightingModel extends BasicLightingModel {
  7095. constructor( specular = true ) {
  7096. super();
  7097. this.specular = specular;
  7098. }
  7099. direct( { lightDirection, lightColor, reflectedLight } ) {
  7100. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  7101. const irradiance = dotNL.mul( lightColor );
  7102. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  7103. if ( this.specular === true ) {
  7104. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  7105. }
  7106. }
  7107. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  7108. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  7109. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  7110. }
  7111. }
  7112. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  7113. class MeshLambertNodeMaterial extends NodeMaterial {
  7114. static get type() {
  7115. return 'MeshLambertNodeMaterial';
  7116. }
  7117. constructor( parameters ) {
  7118. super();
  7119. this.isMeshLambertNodeMaterial = true;
  7120. this.lights = true;
  7121. this.setDefaultValues( _defaultValues$8 );
  7122. this.setValues( parameters );
  7123. }
  7124. setupEnvironment( builder ) {
  7125. const envNode = super.setupEnvironment( builder );
  7126. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  7127. }
  7128. setupLightingModel( /*builder*/ ) {
  7129. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  7130. }
  7131. }
  7132. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  7133. class MeshPhongNodeMaterial extends NodeMaterial {
  7134. static get type() {
  7135. return 'MeshPhongNodeMaterial';
  7136. }
  7137. constructor( parameters ) {
  7138. super();
  7139. this.isMeshPhongNodeMaterial = true;
  7140. this.lights = true;
  7141. this.shininessNode = null;
  7142. this.specularNode = null;
  7143. this.setDefaultValues( _defaultValues$7 );
  7144. this.setValues( parameters );
  7145. }
  7146. setupEnvironment( builder ) {
  7147. const envNode = super.setupEnvironment( builder );
  7148. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  7149. }
  7150. setupLightingModel( /*builder*/ ) {
  7151. return new PhongLightingModel();
  7152. }
  7153. setupVariants() {
  7154. // SHININESS
  7155. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  7156. shininess.assign( shininessNode );
  7157. // SPECULAR COLOR
  7158. const specularNode = this.specularNode || materialSpecular;
  7159. specularColor.assign( specularNode );
  7160. }
  7161. copy( source ) {
  7162. this.shininessNode = source.shininessNode;
  7163. this.specularNode = source.specularNode;
  7164. return super.copy( source );
  7165. }
  7166. }
  7167. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  7168. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  7169. return float( 0 );
  7170. }
  7171. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  7172. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  7173. return geometryRoughness;
  7174. } );
  7175. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  7176. const { roughness } = inputs;
  7177. const geometryRoughness = getGeometryRoughness();
  7178. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  7179. roughnessFactor = roughnessFactor.add( geometryRoughness );
  7180. roughnessFactor = roughnessFactor.min( 1.0 );
  7181. return roughnessFactor;
  7182. } );
  7183. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  7184. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  7185. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  7186. const a2 = alpha.pow2();
  7187. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  7188. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  7189. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  7190. } ).setLayout( {
  7191. name: 'V_GGX_SmithCorrelated',
  7192. type: 'float',
  7193. inputs: [
  7194. { name: 'alpha', type: 'float' },
  7195. { name: 'dotNL', type: 'float' },
  7196. { name: 'dotNV', type: 'float' }
  7197. ]
  7198. } ); // validated
  7199. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  7200. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  7201. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  7202. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  7203. const v = div( 0.5, gv.add( gl ) );
  7204. return v.saturate();
  7205. } ).setLayout( {
  7206. name: 'V_GGX_SmithCorrelated_Anisotropic',
  7207. type: 'float',
  7208. inputs: [
  7209. { name: 'alphaT', type: 'float', qualifier: 'in' },
  7210. { name: 'alphaB', type: 'float', qualifier: 'in' },
  7211. { name: 'dotTV', type: 'float', qualifier: 'in' },
  7212. { name: 'dotBV', type: 'float', qualifier: 'in' },
  7213. { name: 'dotTL', type: 'float', qualifier: 'in' },
  7214. { name: 'dotBL', type: 'float', qualifier: 'in' },
  7215. { name: 'dotNV', type: 'float', qualifier: 'in' },
  7216. { name: 'dotNL', type: 'float', qualifier: 'in' }
  7217. ]
  7218. } );
  7219. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  7220. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  7221. // alpha is "roughness squared" in Disney’s reparameterization
  7222. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  7223. const a2 = alpha.pow2();
  7224. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  7225. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  7226. } ).setLayout( {
  7227. name: 'D_GGX',
  7228. type: 'float',
  7229. inputs: [
  7230. { name: 'alpha', type: 'float' },
  7231. { name: 'dotNH', type: 'float' }
  7232. ]
  7233. } ); // validated
  7234. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  7235. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  7236. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  7237. const a2 = alphaT.mul( alphaB );
  7238. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  7239. const v2 = v.dot( v );
  7240. const w2 = a2.div( v2 );
  7241. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  7242. } ).setLayout( {
  7243. name: 'D_GGX_Anisotropic',
  7244. type: 'float',
  7245. inputs: [
  7246. { name: 'alphaT', type: 'float', qualifier: 'in' },
  7247. { name: 'alphaB', type: 'float', qualifier: 'in' },
  7248. { name: 'dotNH', type: 'float', qualifier: 'in' },
  7249. { name: 'dotTH', type: 'float', qualifier: 'in' },
  7250. { name: 'dotBH', type: 'float', qualifier: 'in' }
  7251. ]
  7252. } );
  7253. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  7254. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  7255. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  7256. const normalView = inputs.normalView || transformedNormalView;
  7257. const alpha = roughness.pow2(); // UE4's roughness
  7258. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  7259. const dotNL = normalView.dot( lightDirection ).clamp();
  7260. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  7261. const dotNH = normalView.dot( halfDir ).clamp();
  7262. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  7263. let F = F_Schlick( { f0, f90, dotVH } );
  7264. let V, D;
  7265. if ( defined( USE_IRIDESCENCE ) ) {
  7266. F = iridescence.mix( F, f );
  7267. }
  7268. if ( defined( USE_ANISOTROPY ) ) {
  7269. const dotTL = anisotropyT.dot( lightDirection );
  7270. const dotTV = anisotropyT.dot( positionViewDirection );
  7271. const dotTH = anisotropyT.dot( halfDir );
  7272. const dotBL = anisotropyB.dot( lightDirection );
  7273. const dotBV = anisotropyB.dot( positionViewDirection );
  7274. const dotBH = anisotropyB.dot( halfDir );
  7275. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  7276. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  7277. } else {
  7278. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  7279. D = D_GGX( { alpha, dotNH } );
  7280. }
  7281. return F.mul( V ).mul( D );
  7282. } ); // validated
  7283. // Analytical approximation of the DFG LUT, one half of the
  7284. // split-sum approximation used in indirect specular lighting.
  7285. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  7286. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  7287. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  7288. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  7289. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  7290. const r = roughness.mul( c0 ).add( c1 );
  7291. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  7292. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  7293. return fab;
  7294. } ).setLayout( {
  7295. name: 'DFGApprox',
  7296. type: 'vec2',
  7297. inputs: [
  7298. { name: 'roughness', type: 'float' },
  7299. { name: 'dotNV', type: 'vec3' }
  7300. ]
  7301. } );
  7302. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  7303. const { dotNV, specularColor, specularF90, roughness } = inputs;
  7304. const fab = DFGApprox( { dotNV, roughness } );
  7305. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  7306. } );
  7307. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  7308. const x = dotVH.oneMinus().saturate();
  7309. const x2 = x.mul( x );
  7310. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  7311. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  7312. } ).setLayout( {
  7313. name: 'Schlick_to_F0',
  7314. type: 'vec3',
  7315. inputs: [
  7316. { name: 'f', type: 'vec3' },
  7317. { name: 'f90', type: 'float' },
  7318. { name: 'dotVH', type: 'float' }
  7319. ]
  7320. } );
  7321. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  7322. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  7323. const alpha = roughness.pow2();
  7324. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  7325. const invAlpha = float( 1.0 ).div( alpha );
  7326. const cos2h = dotNH.pow2();
  7327. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  7328. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  7329. } ).setLayout( {
  7330. name: 'D_Charlie',
  7331. type: 'float',
  7332. inputs: [
  7333. { name: 'roughness', type: 'float' },
  7334. { name: 'dotNH', type: 'float' }
  7335. ]
  7336. } );
  7337. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  7338. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  7339. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  7340. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  7341. } ).setLayout( {
  7342. name: 'V_Neubelt',
  7343. type: 'float',
  7344. inputs: [
  7345. { name: 'dotNV', type: 'float' },
  7346. { name: 'dotNL', type: 'float' }
  7347. ]
  7348. } );
  7349. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  7350. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  7351. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  7352. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  7353. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  7354. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  7355. const V = V_Neubelt( { dotNV, dotNL } );
  7356. return sheen.mul( D ).mul( V );
  7357. } );
  7358. // Rect Area Light
  7359. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  7360. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  7361. // code: https://github.com/selfshadow/ltc_code/
  7362. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  7363. const LUT_SIZE = 64.0;
  7364. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  7365. const LUT_BIAS = 0.5 / LUT_SIZE;
  7366. const dotNV = N.dot( V ).saturate();
  7367. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  7368. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  7369. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  7370. return uv;
  7371. } ).setLayout( {
  7372. name: 'LTC_Uv',
  7373. type: 'vec2',
  7374. inputs: [
  7375. { name: 'N', type: 'vec3' },
  7376. { name: 'V', type: 'vec3' },
  7377. { name: 'roughness', type: 'float' }
  7378. ]
  7379. } );
  7380. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  7381. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  7382. // An approximation of the form factor of a horizon-clipped rectangle.
  7383. const l = f.length();
  7384. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  7385. } ).setLayout( {
  7386. name: 'LTC_ClippedSphereFormFactor',
  7387. type: 'float',
  7388. inputs: [
  7389. { name: 'f', type: 'vec3' }
  7390. ]
  7391. } );
  7392. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  7393. const x = v1.dot( v2 );
  7394. const y = x.abs().toVar();
  7395. // rational polynomial approximation to theta / sin( theta ) / 2PI
  7396. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  7397. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  7398. const v = a.div( b );
  7399. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  7400. return v1.cross( v2 ).mul( theta_sintheta );
  7401. } ).setLayout( {
  7402. name: 'LTC_EdgeVectorFormFactor',
  7403. type: 'vec3',
  7404. inputs: [
  7405. { name: 'v1', type: 'vec3' },
  7406. { name: 'v2', type: 'vec3' }
  7407. ]
  7408. } );
  7409. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  7410. // bail if point is on back side of plane of light
  7411. // assumes ccw winding order of light vertices
  7412. const v1 = p1.sub( p0 ).toVar();
  7413. const v2 = p3.sub( p0 ).toVar();
  7414. const lightNormal = v1.cross( v2 );
  7415. const result = vec3().toVar();
  7416. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  7417. // construct orthonormal basis around N
  7418. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  7419. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  7420. // compute transform
  7421. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  7422. // transform rect
  7423. // & project rect onto sphere
  7424. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  7425. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  7426. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  7427. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  7428. // calculate vector form factor
  7429. const vectorFormFactor = vec3( 0 ).toVar();
  7430. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  7431. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  7432. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  7433. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  7434. // adjust for horizon clipping
  7435. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  7436. } );
  7437. return result;
  7438. } ).setLayout( {
  7439. name: 'LTC_Evaluate',
  7440. type: 'vec3',
  7441. inputs: [
  7442. { name: 'N', type: 'vec3' },
  7443. { name: 'V', type: 'vec3' },
  7444. { name: 'P', type: 'vec3' },
  7445. { name: 'mInv', type: 'mat3' },
  7446. { name: 'p0', type: 'vec3' },
  7447. { name: 'p1', type: 'vec3' },
  7448. { name: 'p2', type: 'vec3' },
  7449. { name: 'p3', type: 'vec3' }
  7450. ]
  7451. } );
  7452. // Mipped Bicubic Texture Filtering by N8
  7453. // https://www.shadertoy.com/view/Dl2SDW
  7454. const bC = 1.0 / 6.0;
  7455. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  7456. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  7457. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  7458. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  7459. const g0 = ( a ) => w0( a ).add( w1( a ) );
  7460. const g1 = ( a ) => w2( a ).add( w3( a ) );
  7461. // h0 and h1 are the two offset functions
  7462. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  7463. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  7464. const bicubic = ( textureNode, texelSize, lod ) => {
  7465. const uv = textureNode.uvNode;
  7466. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  7467. const iuv = floor( uvScaled );
  7468. const fuv = fract( uvScaled );
  7469. const g0x = g0( fuv.x );
  7470. const g1x = g1( fuv.x );
  7471. const h0x = h0( fuv.x );
  7472. const h1x = h1( fuv.x );
  7473. const h0y = h0( fuv.y );
  7474. const h1y = h1( fuv.y );
  7475. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  7476. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  7477. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  7478. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  7479. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.uv( p0 ).level( lod ) ), g1x.mul( textureNode.uv( p1 ).level( lod ) ) ) );
  7480. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.uv( p2 ).level( lod ) ), g1x.mul( textureNode.uv( p3 ).level( lod ) ) ) );
  7481. return a.add( b );
  7482. };
  7483. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  7484. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  7485. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  7486. const fLodSizeInv = div( 1.0, fLodSize );
  7487. const cLodSizeInv = div( 1.0, cLodSize );
  7488. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  7489. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  7490. return fract( lodNode ).mix( fSample, cSample );
  7491. } );
  7492. //
  7493. // Transmission
  7494. //
  7495. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  7496. // Direction of refracted light.
  7497. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  7498. // Compute rotation-independent scaling of the model matrix.
  7499. const modelScale = vec3(
  7500. length( modelMatrix[ 0 ].xyz ),
  7501. length( modelMatrix[ 1 ].xyz ),
  7502. length( modelMatrix[ 2 ].xyz )
  7503. );
  7504. // The thickness is specified in local space.
  7505. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  7506. } ).setLayout( {
  7507. name: 'getVolumeTransmissionRay',
  7508. type: 'vec3',
  7509. inputs: [
  7510. { name: 'n', type: 'vec3' },
  7511. { name: 'v', type: 'vec3' },
  7512. { name: 'thickness', type: 'float' },
  7513. { name: 'ior', type: 'float' },
  7514. { name: 'modelMatrix', type: 'mat4' }
  7515. ]
  7516. } );
  7517. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  7518. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  7519. // an IOR of 1.5 results in the default amount of microfacet refraction.
  7520. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  7521. } ).setLayout( {
  7522. name: 'applyIorToRoughness',
  7523. type: 'float',
  7524. inputs: [
  7525. { name: 'roughness', type: 'float' },
  7526. { name: 'ior', type: 'float' }
  7527. ]
  7528. } );
  7529. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  7530. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  7531. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  7532. const vTexture = material.side == BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  7533. const transmissionSample = vTexture.uv( fragCoord );
  7534. //const transmissionSample = viewportMipTexture( fragCoord );
  7535. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  7536. return textureBicubic( transmissionSample, lod );
  7537. } );
  7538. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  7539. If( attenuationDistance.notEqual( 0 ), () => {
  7540. // Compute light attenuation using Beer's law.
  7541. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  7542. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  7543. return transmittance;
  7544. } );
  7545. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  7546. return vec3( 1.0 );
  7547. } ).setLayout( {
  7548. name: 'volumeAttenuation',
  7549. type: 'vec3',
  7550. inputs: [
  7551. { name: 'transmissionDistance', type: 'float' },
  7552. { name: 'attenuationColor', type: 'vec3' },
  7553. { name: 'attenuationDistance', type: 'float' }
  7554. ]
  7555. } );
  7556. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  7557. let transmittedLight, transmittance;
  7558. if ( dispersion ) {
  7559. transmittedLight = vec4().toVar();
  7560. transmittance = vec3().toVar();
  7561. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  7562. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  7563. Loop( { start: 0, end: 3 }, ( { i } ) => {
  7564. const ior = iors.element( i );
  7565. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  7566. const refractedRayExit = position.add( transmissionRay );
  7567. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  7568. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  7569. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  7570. refractionCoords.addAssign( 1.0 );
  7571. refractionCoords.divAssign( 2.0 );
  7572. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  7573. // Sample framebuffer to get pixel the refracted ray hits.
  7574. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  7575. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  7576. transmittedLight.a.addAssign( transmissionSample.a );
  7577. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  7578. } );
  7579. transmittedLight.a.divAssign( 3.0 );
  7580. } else {
  7581. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  7582. const refractedRayExit = position.add( transmissionRay );
  7583. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  7584. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  7585. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  7586. refractionCoords.addAssign( 1.0 );
  7587. refractionCoords.divAssign( 2.0 );
  7588. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  7589. // Sample framebuffer to get pixel the refracted ray hits.
  7590. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  7591. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  7592. }
  7593. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  7594. const dotNV = n.dot( v ).clamp();
  7595. // Get the specular component.
  7596. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  7597. dotNV,
  7598. specularColor,
  7599. specularF90,
  7600. roughness
  7601. } ) );
  7602. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  7603. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  7604. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  7605. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  7606. } );
  7607. //
  7608. // Iridescence
  7609. //
  7610. // XYZ to linear-sRGB color space
  7611. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  7612. 3.2404542, - 0.9692660, 0.0556434,
  7613. - 1.5371385, 1.8760108, - 0.2040259,
  7614. - 0.4985314, 0.0415560, 1.0572252
  7615. );
  7616. // Assume air interface for top
  7617. // Note: We don't handle the case fresnel0 == 1
  7618. const Fresnel0ToIor = ( fresnel0 ) => {
  7619. const sqrtF0 = fresnel0.sqrt();
  7620. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  7621. };
  7622. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  7623. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  7624. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  7625. };
  7626. // Fresnel equations for dielectric/dielectric interfaces.
  7627. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  7628. // Evaluation XYZ sensitivity curves in Fourier space
  7629. const evalSensitivity = ( OPD, shift ) => {
  7630. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  7631. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  7632. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  7633. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  7634. 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() );
  7635. 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() );
  7636. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  7637. const rgb = XYZ_TO_REC709.mul( xyz );
  7638. return rgb;
  7639. };
  7640. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  7641. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  7642. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  7643. // Evaluate the cosTheta on the base layer (Snell law)
  7644. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  7645. // Handle TIR:
  7646. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  7647. If( cosTheta2Sq.lessThan( 0 ), () => {
  7648. return vec3( 1.0 );
  7649. } );
  7650. const cosTheta2 = cosTheta2Sq.sqrt();
  7651. // First interface
  7652. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  7653. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  7654. //const R21 = R12;
  7655. const T121 = R12.oneMinus();
  7656. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  7657. const phi21 = float( Math.PI ).sub( phi12 );
  7658. // Second interface
  7659. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  7660. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  7661. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  7662. const phi23 = vec3(
  7663. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  7664. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  7665. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  7666. );
  7667. // Phase shift
  7668. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  7669. const phi = vec3( phi21 ).add( phi23 );
  7670. // Compound terms
  7671. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  7672. const r123 = R123.sqrt();
  7673. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  7674. // Reflectance term for m = 0 (DC term amplitude)
  7675. const C0 = R12.add( Rs );
  7676. const I = C0.toVar();
  7677. // Reflectance term for m > 0 (pairs of diracs)
  7678. const Cm = Rs.sub( T121 ).toVar();
  7679. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  7680. Cm.mulAssign( r123 );
  7681. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  7682. I.addAssign( Cm.mul( Sm ) );
  7683. } );
  7684. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  7685. return I.max( vec3( 0.0 ) );
  7686. } ).setLayout( {
  7687. name: 'evalIridescence',
  7688. type: 'vec3',
  7689. inputs: [
  7690. { name: 'outsideIOR', type: 'float' },
  7691. { name: 'eta2', type: 'float' },
  7692. { name: 'cosTheta1', type: 'float' },
  7693. { name: 'thinFilmThickness', type: 'float' },
  7694. { name: 'baseF0', type: 'vec3' }
  7695. ]
  7696. } );
  7697. //
  7698. // Sheen
  7699. //
  7700. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  7701. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  7702. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  7703. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  7704. const dotNV = normal.dot( viewDir ).saturate();
  7705. const r2 = roughness.pow2();
  7706. const a = select(
  7707. roughness.lessThan( 0.25 ),
  7708. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  7709. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  7710. );
  7711. const b = select(
  7712. roughness.lessThan( 0.25 ),
  7713. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  7714. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  7715. );
  7716. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  7717. return DG.mul( 1.0 / Math.PI ).saturate();
  7718. } );
  7719. const clearcoatF0 = vec3( 0.04 );
  7720. const clearcoatF90 = float( 1 );
  7721. //
  7722. class PhysicalLightingModel extends LightingModel {
  7723. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  7724. super();
  7725. this.clearcoat = clearcoat;
  7726. this.sheen = sheen;
  7727. this.iridescence = iridescence;
  7728. this.anisotropy = anisotropy;
  7729. this.transmission = transmission;
  7730. this.dispersion = dispersion;
  7731. this.clearcoatRadiance = null;
  7732. this.clearcoatSpecularDirect = null;
  7733. this.clearcoatSpecularIndirect = null;
  7734. this.sheenSpecularDirect = null;
  7735. this.sheenSpecularIndirect = null;
  7736. this.iridescenceFresnel = null;
  7737. this.iridescenceF0 = null;
  7738. }
  7739. start( context ) {
  7740. if ( this.clearcoat === true ) {
  7741. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  7742. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  7743. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  7744. }
  7745. if ( this.sheen === true ) {
  7746. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  7747. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  7748. }
  7749. if ( this.iridescence === true ) {
  7750. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  7751. this.iridescenceFresnel = evalIridescence( {
  7752. outsideIOR: float( 1.0 ),
  7753. eta2: iridescenceIOR,
  7754. cosTheta1: dotNVi,
  7755. thinFilmThickness: iridescenceThickness,
  7756. baseF0: specularColor
  7757. } );
  7758. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  7759. }
  7760. if ( this.transmission === true ) {
  7761. const position = positionWorld;
  7762. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  7763. const n = transformedNormalWorld;
  7764. context.backdrop = getIBLVolumeRefraction(
  7765. n,
  7766. v,
  7767. roughness,
  7768. diffuseColor,
  7769. specularColor,
  7770. specularF90, // specularF90
  7771. position, // positionWorld
  7772. modelWorldMatrix, // modelMatrix
  7773. cameraViewMatrix, // viewMatrix
  7774. cameraProjectionMatrix, // projMatrix
  7775. ior,
  7776. thickness,
  7777. attenuationColor,
  7778. attenuationDistance,
  7779. this.dispersion ? dispersion : null
  7780. );
  7781. context.backdropAlpha = transmission;
  7782. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  7783. }
  7784. }
  7785. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  7786. // Approximates multi-scattering in order to preserve energy.
  7787. // http://www.jcgt.org/published/0008/01/03/
  7788. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  7789. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  7790. const fab = DFGApprox( { roughness, dotNV } );
  7791. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  7792. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  7793. const Ess = fab.x.add( fab.y );
  7794. const Ems = Ess.oneMinus();
  7795. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  7796. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  7797. singleScatter.addAssign( FssEss );
  7798. multiScatter.addAssign( Fms.mul( Ems ) );
  7799. }
  7800. direct( { lightDirection, lightColor, reflectedLight } ) {
  7801. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  7802. const irradiance = dotNL.mul( lightColor );
  7803. if ( this.sheen === true ) {
  7804. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  7805. }
  7806. if ( this.clearcoat === true ) {
  7807. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  7808. const ccIrradiance = dotNLcc.mul( lightColor );
  7809. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  7810. }
  7811. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  7812. 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 } ) ) );
  7813. }
  7814. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  7815. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  7816. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  7817. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  7818. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  7819. const N = transformedNormalView;
  7820. const V = positionViewDirection;
  7821. const P = positionView.toVar();
  7822. const uv = LTC_Uv( { N, V, roughness } );
  7823. const t1 = ltc_1.uv( uv ).toVar();
  7824. const t2 = ltc_2.uv( uv ).toVar();
  7825. const mInv = mat3(
  7826. vec3( t1.x, 0, t1.y ),
  7827. vec3( 0, 1, 0 ),
  7828. vec3( t1.z, 0, t1.w )
  7829. ).toVar();
  7830. // LTC Fresnel Approximation by Stephen Hill
  7831. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  7832. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  7833. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  7834. 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 } ) ) );
  7835. }
  7836. indirect( context, stack, builder ) {
  7837. this.indirectDiffuse( context, stack, builder );
  7838. this.indirectSpecular( context, stack, builder );
  7839. this.ambientOcclusion( context, stack, builder );
  7840. }
  7841. indirectDiffuse( { irradiance, reflectedLight } ) {
  7842. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  7843. }
  7844. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  7845. if ( this.sheen === true ) {
  7846. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  7847. sheen,
  7848. IBLSheenBRDF( {
  7849. normal: transformedNormalView,
  7850. viewDir: positionViewDirection,
  7851. roughness: sheenRoughness
  7852. } )
  7853. ) );
  7854. }
  7855. if ( this.clearcoat === true ) {
  7856. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  7857. const clearcoatEnv = EnvironmentBRDF( {
  7858. dotNV: dotNVcc,
  7859. specularColor: clearcoatF0,
  7860. specularF90: clearcoatF90,
  7861. roughness: clearcoatRoughness
  7862. } );
  7863. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  7864. }
  7865. // Both indirect specular and indirect diffuse light accumulate here
  7866. const singleScattering = vec3().toVar( 'singleScattering' );
  7867. const multiScattering = vec3().toVar( 'multiScattering' );
  7868. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  7869. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  7870. const totalScattering = singleScattering.add( multiScattering );
  7871. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  7872. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  7873. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  7874. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  7875. }
  7876. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  7877. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  7878. const aoNV = dotNV.add( ambientOcclusion );
  7879. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  7880. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  7881. if ( this.clearcoat === true ) {
  7882. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  7883. }
  7884. if ( this.sheen === true ) {
  7885. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  7886. }
  7887. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  7888. reflectedLight.indirectSpecular.mulAssign( aoNode );
  7889. }
  7890. finish( context ) {
  7891. const { outgoingLight } = context;
  7892. if ( this.clearcoat === true ) {
  7893. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  7894. const Fcc = F_Schlick( {
  7895. dotVH: dotNVcc,
  7896. f0: clearcoatF0,
  7897. f90: clearcoatF90
  7898. } );
  7899. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  7900. outgoingLight.assign( clearcoatLight );
  7901. }
  7902. if ( this.sheen === true ) {
  7903. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  7904. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  7905. outgoingLight.assign( sheenLight );
  7906. }
  7907. }
  7908. }
  7909. // These defines must match with PMREMGenerator
  7910. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  7911. const cubeUV_m0 = /*@__PURE__*/ float( - 2.0 );
  7912. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  7913. const cubeUV_m1 = /*@__PURE__*/ float( - 1.0 );
  7914. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  7915. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  7916. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  7917. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  7918. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  7919. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  7920. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  7921. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  7922. // These shader functions convert between the UV coordinates of a single face of
  7923. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  7924. // sampling a textureCube (not generally normalized ).
  7925. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  7926. const absDirection = vec3( abs( direction ) ).toVar();
  7927. const face = float( - 1.0 ).toVar();
  7928. If( absDirection.x.greaterThan( absDirection.z ), () => {
  7929. If( absDirection.x.greaterThan( absDirection.y ), () => {
  7930. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  7931. } ).Else( () => {
  7932. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  7933. } );
  7934. } ).Else( () => {
  7935. If( absDirection.z.greaterThan( absDirection.y ), () => {
  7936. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  7937. } ).Else( () => {
  7938. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  7939. } );
  7940. } );
  7941. return face;
  7942. } ).setLayout( {
  7943. name: 'getFace',
  7944. type: 'float',
  7945. inputs: [
  7946. { name: 'direction', type: 'vec3' }
  7947. ]
  7948. } );
  7949. // RH coordinate system; PMREM face-indexing convention
  7950. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  7951. const uv = vec2().toVar();
  7952. If( face.equal( 0.0 ), () => {
  7953. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  7954. } ).ElseIf( face.equal( 1.0 ), () => {
  7955. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  7956. } ).ElseIf( face.equal( 2.0 ), () => {
  7957. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  7958. } ).ElseIf( face.equal( 3.0 ), () => {
  7959. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  7960. } ).ElseIf( face.equal( 4.0 ), () => {
  7961. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  7962. } ).Else( () => {
  7963. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  7964. } );
  7965. return mul( 0.5, uv.add( 1.0 ) );
  7966. } ).setLayout( {
  7967. name: 'getUV',
  7968. type: 'vec2',
  7969. inputs: [
  7970. { name: 'direction', type: 'vec3' },
  7971. { name: 'face', type: 'float' }
  7972. ]
  7973. } );
  7974. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  7975. const mip = float( 0.0 ).toVar();
  7976. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  7977. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  7978. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  7979. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  7980. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  7981. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  7982. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  7983. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  7984. } ).Else( () => {
  7985. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  7986. } );
  7987. return mip;
  7988. } ).setLayout( {
  7989. name: 'roughnessToMip',
  7990. type: 'float',
  7991. inputs: [
  7992. { name: 'roughness', type: 'float' }
  7993. ]
  7994. } );
  7995. // RH coordinate system; PMREM face-indexing convention
  7996. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  7997. const uv = uv_immutable.toVar();
  7998. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  7999. const direction = vec3( uv, 1.0 ).toVar();
  8000. If( face.equal( 0.0 ), () => {
  8001. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  8002. } ).ElseIf( face.equal( 1.0 ), () => {
  8003. direction.assign( direction.xzy );
  8004. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  8005. } ).ElseIf( face.equal( 2.0 ), () => {
  8006. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  8007. } ).ElseIf( face.equal( 3.0 ), () => {
  8008. direction.assign( direction.zyx );
  8009. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  8010. } ).ElseIf( face.equal( 4.0 ), () => {
  8011. direction.assign( direction.xzy );
  8012. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  8013. } ).ElseIf( face.equal( 5.0 ), () => {
  8014. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  8015. } );
  8016. return direction;
  8017. } ).setLayout( {
  8018. name: 'getDirection',
  8019. type: 'vec3',
  8020. inputs: [
  8021. { name: 'uv', type: 'vec2' },
  8022. { name: 'face', type: 'float' }
  8023. ]
  8024. } );
  8025. //
  8026. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  8027. const roughness = float( roughness_immutable );
  8028. const sampleDir = vec3( sampleDir_immutable );
  8029. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  8030. const mipF = fract( mip );
  8031. const mipInt = floor( mip );
  8032. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  8033. If( mipF.notEqual( 0.0 ), () => {
  8034. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  8035. color0.assign( mix( color0, color1, mipF ) );
  8036. } );
  8037. return color0;
  8038. } );
  8039. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  8040. const mipInt = float( mipInt_immutable ).toVar();
  8041. const direction = vec3( direction_immutable );
  8042. const face = float( getFace( direction ) ).toVar();
  8043. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  8044. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  8045. const faceSize = float( exp2( mipInt ) ).toVar();
  8046. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  8047. If( face.greaterThan( 2.0 ), () => {
  8048. uv.y.addAssign( faceSize );
  8049. face.subAssign( 3.0 );
  8050. } );
  8051. uv.x.addAssign( face.mul( faceSize ) );
  8052. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  8053. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  8054. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  8055. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  8056. return envMap.uv( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  8057. } );
  8058. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  8059. const cosTheta = cos( theta );
  8060. // Rodrigues' axis-angle rotation
  8061. const sampleDirection = outputDirection.mul( cosTheta )
  8062. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  8063. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  8064. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  8065. } );
  8066. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  8067. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  8068. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  8069. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  8070. } );
  8071. axis.assign( normalize( axis ) );
  8072. const gl_FragColor = vec3().toVar();
  8073. 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 } ) ) );
  8074. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  8075. If( i.greaterThanEqual( samples ), () => {
  8076. Break();
  8077. } );
  8078. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  8079. 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 } ) ) );
  8080. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  8081. } );
  8082. return vec4( gl_FragColor, 1 );
  8083. } );
  8084. let _generator = null;
  8085. const _cache = new WeakMap();
  8086. function _generateCubeUVSize( imageHeight ) {
  8087. const maxMip = Math.log2( imageHeight ) - 2;
  8088. const texelHeight = 1.0 / imageHeight;
  8089. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  8090. return { texelWidth, texelHeight, maxMip };
  8091. }
  8092. function _getPMREMFromTexture( texture ) {
  8093. let cacheTexture = _cache.get( texture );
  8094. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  8095. if ( pmremVersion !== texture.pmremVersion ) {
  8096. const image = texture.image;
  8097. if ( texture.isCubeTexture ) {
  8098. if ( isCubeMapReady( image ) ) {
  8099. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  8100. } else {
  8101. return null;
  8102. }
  8103. } else {
  8104. if ( isEquirectangularMapReady( image ) ) {
  8105. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  8106. } else {
  8107. return null;
  8108. }
  8109. }
  8110. cacheTexture.pmremVersion = texture.pmremVersion;
  8111. _cache.set( texture, cacheTexture );
  8112. }
  8113. return cacheTexture.texture;
  8114. }
  8115. class PMREMNode extends TempNode {
  8116. static get type() {
  8117. return 'PMREMNode';
  8118. }
  8119. constructor( value, uvNode = null, levelNode = null ) {
  8120. super( 'vec3' );
  8121. this._value = value;
  8122. this._pmrem = null;
  8123. this.uvNode = uvNode;
  8124. this.levelNode = levelNode;
  8125. this._generator = null;
  8126. const defaultTexture = new Texture();
  8127. defaultTexture.isRenderTargetTexture = true;
  8128. this._texture = texture( defaultTexture );
  8129. this._width = uniform( 0 );
  8130. this._height = uniform( 0 );
  8131. this._maxMip = uniform( 0 );
  8132. this.updateBeforeType = NodeUpdateType.RENDER;
  8133. }
  8134. set value( value ) {
  8135. this._value = value;
  8136. this._pmrem = null;
  8137. }
  8138. get value() {
  8139. return this._value;
  8140. }
  8141. updateFromTexture( texture ) {
  8142. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  8143. this._texture.value = texture;
  8144. this._width.value = cubeUVSize.texelWidth;
  8145. this._height.value = cubeUVSize.texelHeight;
  8146. this._maxMip.value = cubeUVSize.maxMip;
  8147. }
  8148. updateBefore() {
  8149. let pmrem = this._pmrem;
  8150. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  8151. const texture = this._value;
  8152. if ( pmremVersion !== texture.pmremVersion ) {
  8153. if ( texture.isPMREMTexture === true ) {
  8154. pmrem = texture;
  8155. } else {
  8156. pmrem = _getPMREMFromTexture( texture );
  8157. }
  8158. if ( pmrem !== null ) {
  8159. this._pmrem = pmrem;
  8160. this.updateFromTexture( pmrem );
  8161. }
  8162. }
  8163. }
  8164. setup( builder ) {
  8165. if ( _generator === null ) {
  8166. _generator = builder.createPMREMGenerator();
  8167. }
  8168. //
  8169. this.updateBefore( builder );
  8170. //
  8171. let uvNode = this.uvNode;
  8172. if ( uvNode === null && builder.context.getUV ) {
  8173. uvNode = builder.context.getUV( this );
  8174. }
  8175. //
  8176. const texture = this.value;
  8177. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  8178. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  8179. }
  8180. //
  8181. let levelNode = this.levelNode;
  8182. if ( levelNode === null && builder.context.getTextureLevel ) {
  8183. levelNode = builder.context.getTextureLevel( this );
  8184. }
  8185. //
  8186. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  8187. }
  8188. }
  8189. function isCubeMapReady( image ) {
  8190. if ( image === null || image === undefined ) return false;
  8191. let count = 0;
  8192. const length = 6;
  8193. for ( let i = 0; i < length; i ++ ) {
  8194. if ( image[ i ] !== undefined ) count ++;
  8195. }
  8196. return count === length;
  8197. }
  8198. function isEquirectangularMapReady( image ) {
  8199. if ( image === null || image === undefined ) return false;
  8200. return image.height > 0;
  8201. }
  8202. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode );
  8203. const _envNodeCache = new WeakMap();
  8204. class EnvironmentNode extends LightingNode {
  8205. static get type() {
  8206. return 'EnvironmentNode';
  8207. }
  8208. constructor( envNode = null ) {
  8209. super();
  8210. this.envNode = envNode;
  8211. }
  8212. setup( builder ) {
  8213. const { material } = builder;
  8214. let envNode = this.envNode;
  8215. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  8216. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  8217. let cacheEnvNode = _envNodeCache.get( value );
  8218. if ( cacheEnvNode === undefined ) {
  8219. cacheEnvNode = pmremTexture( value );
  8220. _envNodeCache.set( value, cacheEnvNode );
  8221. }
  8222. envNode = cacheEnvNode;
  8223. }
  8224. //
  8225. const envMap = material.envMap;
  8226. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  8227. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  8228. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  8229. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  8230. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  8231. const isolateRadiance = cache( radiance );
  8232. const isolateIrradiance = cache( irradiance );
  8233. //
  8234. builder.context.radiance.addAssign( isolateRadiance );
  8235. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  8236. //
  8237. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  8238. if ( clearcoatRadiance ) {
  8239. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  8240. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  8241. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  8242. }
  8243. }
  8244. }
  8245. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  8246. let reflectVec = null;
  8247. return {
  8248. getUV: () => {
  8249. if ( reflectVec === null ) {
  8250. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  8251. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  8252. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  8253. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  8254. }
  8255. return reflectVec;
  8256. },
  8257. getTextureLevel: () => {
  8258. return roughnessNode;
  8259. }
  8260. };
  8261. };
  8262. const createIrradianceContext = ( normalWorldNode ) => {
  8263. return {
  8264. getUV: () => {
  8265. return normalWorldNode;
  8266. },
  8267. getTextureLevel: () => {
  8268. return float( 1.0 );
  8269. }
  8270. };
  8271. };
  8272. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  8273. class MeshStandardNodeMaterial extends NodeMaterial {
  8274. static get type() {
  8275. return 'MeshStandardNodeMaterial';
  8276. }
  8277. constructor( parameters ) {
  8278. super();
  8279. this.isMeshStandardNodeMaterial = true;
  8280. this.lights = true;
  8281. this.emissiveNode = null;
  8282. this.metalnessNode = null;
  8283. this.roughnessNode = null;
  8284. this.setDefaultValues( _defaultValues$6 );
  8285. this.setValues( parameters );
  8286. }
  8287. setupEnvironment( builder ) {
  8288. let envNode = super.setupEnvironment( builder );
  8289. if ( envNode === null && builder.environmentNode ) {
  8290. envNode = builder.environmentNode;
  8291. }
  8292. return envNode ? new EnvironmentNode( envNode ) : null;
  8293. }
  8294. setupLightingModel( /*builder*/ ) {
  8295. return new PhysicalLightingModel();
  8296. }
  8297. setupSpecular() {
  8298. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  8299. specularColor.assign( specularColorNode );
  8300. specularF90.assign( 1.0 );
  8301. }
  8302. setupVariants() {
  8303. // METALNESS
  8304. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  8305. metalness.assign( metalnessNode );
  8306. // ROUGHNESS
  8307. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  8308. roughnessNode = getRoughness( { roughness: roughnessNode } );
  8309. roughness.assign( roughnessNode );
  8310. // SPECULAR COLOR
  8311. this.setupSpecular();
  8312. // DIFFUSE COLOR
  8313. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  8314. }
  8315. copy( source ) {
  8316. this.emissiveNode = source.emissiveNode;
  8317. this.metalnessNode = source.metalnessNode;
  8318. this.roughnessNode = source.roughnessNode;
  8319. return super.copy( source );
  8320. }
  8321. }
  8322. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  8323. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  8324. static get type() {
  8325. return 'MeshPhysicalNodeMaterial';
  8326. }
  8327. constructor( parameters ) {
  8328. super();
  8329. this.isMeshPhysicalNodeMaterial = true;
  8330. this.clearcoatNode = null;
  8331. this.clearcoatRoughnessNode = null;
  8332. this.clearcoatNormalNode = null;
  8333. this.sheenNode = null;
  8334. this.sheenRoughnessNode = null;
  8335. this.iridescenceNode = null;
  8336. this.iridescenceIORNode = null;
  8337. this.iridescenceThicknessNode = null;
  8338. this.specularIntensityNode = null;
  8339. this.specularColorNode = null;
  8340. this.iorNode = null;
  8341. this.transmissionNode = null;
  8342. this.thicknessNode = null;
  8343. this.attenuationDistanceNode = null;
  8344. this.attenuationColorNode = null;
  8345. this.dispersionNode = null;
  8346. this.anisotropyNode = null;
  8347. this.setDefaultValues( _defaultValues$5 );
  8348. this.setValues( parameters );
  8349. }
  8350. get useClearcoat() {
  8351. return this.clearcoat > 0 || this.clearcoatNode !== null;
  8352. }
  8353. get useIridescence() {
  8354. return this.iridescence > 0 || this.iridescenceNode !== null;
  8355. }
  8356. get useSheen() {
  8357. return this.sheen > 0 || this.sheenNode !== null;
  8358. }
  8359. get useAnisotropy() {
  8360. return this.anisotropy > 0 || this.anisotropyNode !== null;
  8361. }
  8362. get useTransmission() {
  8363. return this.transmission > 0 || this.transmissionNode !== null;
  8364. }
  8365. get useDispersion() {
  8366. return this.dispersion > 0 || this.dispersionNode !== null;
  8367. }
  8368. setupSpecular() {
  8369. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  8370. ior.assign( iorNode );
  8371. 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 ) );
  8372. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  8373. }
  8374. setupLightingModel( /*builder*/ ) {
  8375. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  8376. }
  8377. setupVariants( builder ) {
  8378. super.setupVariants( builder );
  8379. // CLEARCOAT
  8380. if ( this.useClearcoat ) {
  8381. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  8382. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  8383. clearcoat.assign( clearcoatNode );
  8384. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  8385. }
  8386. // SHEEN
  8387. if ( this.useSheen ) {
  8388. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  8389. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  8390. sheen.assign( sheenNode );
  8391. sheenRoughness.assign( sheenRoughnessNode );
  8392. }
  8393. // IRIDESCENCE
  8394. if ( this.useIridescence ) {
  8395. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  8396. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  8397. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  8398. iridescence.assign( iridescenceNode );
  8399. iridescenceIOR.assign( iridescenceIORNode );
  8400. iridescenceThickness.assign( iridescenceThicknessNode );
  8401. }
  8402. // ANISOTROPY
  8403. if ( this.useAnisotropy ) {
  8404. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  8405. anisotropy.assign( anisotropyV.length() );
  8406. If( anisotropy.equal( 0.0 ), () => {
  8407. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  8408. } ).Else( () => {
  8409. anisotropyV.divAssign( vec2( anisotropy ) );
  8410. anisotropy.assign( anisotropy.saturate() );
  8411. } );
  8412. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  8413. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  8414. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  8415. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  8416. }
  8417. // TRANSMISSION
  8418. if ( this.useTransmission ) {
  8419. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  8420. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  8421. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  8422. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  8423. transmission.assign( transmissionNode );
  8424. thickness.assign( thicknessNode );
  8425. attenuationDistance.assign( attenuationDistanceNode );
  8426. attenuationColor.assign( attenuationColorNode );
  8427. if ( this.useDispersion ) {
  8428. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  8429. dispersion.assign( dispersionNode );
  8430. }
  8431. }
  8432. }
  8433. setupClearcoatNormal() {
  8434. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  8435. }
  8436. setup( builder ) {
  8437. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  8438. super.setup( builder );
  8439. }
  8440. copy( source ) {
  8441. this.clearcoatNode = source.clearcoatNode;
  8442. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  8443. this.clearcoatNormalNode = source.clearcoatNormalNode;
  8444. this.sheenNode = source.sheenNode;
  8445. this.sheenRoughnessNode = source.sheenRoughnessNode;
  8446. this.iridescenceNode = source.iridescenceNode;
  8447. this.iridescenceIORNode = source.iridescenceIORNode;
  8448. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  8449. this.specularIntensityNode = source.specularIntensityNode;
  8450. this.specularColorNode = source.specularColorNode;
  8451. this.transmissionNode = source.transmissionNode;
  8452. this.thicknessNode = source.thicknessNode;
  8453. this.attenuationDistanceNode = source.attenuationDistanceNode;
  8454. this.attenuationColorNode = source.attenuationColorNode;
  8455. this.dispersionNode = source.dispersionNode;
  8456. this.anisotropyNode = source.anisotropyNode;
  8457. return super.copy( source );
  8458. }
  8459. }
  8460. class SSSLightingModel extends PhysicalLightingModel {
  8461. constructor( useClearcoat, useSheen, useIridescence, useSSS ) {
  8462. super( useClearcoat, useSheen, useIridescence );
  8463. this.useSSS = useSSS;
  8464. }
  8465. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  8466. if ( this.useSSS === true ) {
  8467. const material = builder.material;
  8468. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  8469. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  8470. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  8471. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  8472. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  8473. }
  8474. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  8475. }
  8476. }
  8477. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  8478. static get type() {
  8479. return 'MeshSSSNodeMaterial';
  8480. }
  8481. constructor( parameters ) {
  8482. super( parameters );
  8483. this.thicknessColorNode = null;
  8484. this.thicknessDistortionNode = float( 0.1 );
  8485. this.thicknessAmbientNode = float( 0.0 );
  8486. this.thicknessAttenuationNode = float( .1 );
  8487. this.thicknessPowerNode = float( 2.0 );
  8488. this.thicknessScaleNode = float( 10.0 );
  8489. }
  8490. get useSSS() {
  8491. return this.thicknessColorNode !== null;
  8492. }
  8493. setupLightingModel( /*builder*/ ) {
  8494. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useSSS );
  8495. }
  8496. copy( source ) {
  8497. this.thicknessColorNode = source.thicknessColorNode;
  8498. this.thicknessDistortionNode = source.thicknessDistortionNode;
  8499. this.thicknessAmbientNode = source.thicknessAmbientNode;
  8500. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  8501. this.thicknessPowerNode = source.thicknessPowerNode;
  8502. this.thicknessScaleNode = source.thicknessScaleNode;
  8503. return super.copy( source );
  8504. }
  8505. }
  8506. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  8507. // dotNL will be from -1.0 to 1.0
  8508. const dotNL = normal.dot( lightDirection );
  8509. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  8510. if ( builder.material.gradientMap ) {
  8511. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  8512. return vec3( gradientMap.r );
  8513. } else {
  8514. const fw = coord.fwidth().mul( 0.5 );
  8515. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  8516. }
  8517. } );
  8518. class ToonLightingModel extends LightingModel {
  8519. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  8520. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  8521. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  8522. }
  8523. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  8524. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  8525. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  8526. }
  8527. }
  8528. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  8529. class MeshToonNodeMaterial extends NodeMaterial {
  8530. static get type() {
  8531. return 'MeshToonNodeMaterial';
  8532. }
  8533. constructor( parameters ) {
  8534. super();
  8535. this.isMeshToonNodeMaterial = true;
  8536. this.lights = true;
  8537. this.setDefaultValues( _defaultValues$4 );
  8538. this.setValues( parameters );
  8539. }
  8540. setupLightingModel( /*builder*/ ) {
  8541. return new ToonLightingModel();
  8542. }
  8543. }
  8544. class MatcapUVNode extends TempNode {
  8545. static get type() {
  8546. return 'MatcapUVNode';
  8547. }
  8548. constructor() {
  8549. super( 'vec2' );
  8550. }
  8551. setup() {
  8552. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  8553. const y = positionViewDirection.cross( x );
  8554. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  8555. }
  8556. }
  8557. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  8558. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  8559. class MeshMatcapNodeMaterial extends NodeMaterial {
  8560. static get type() {
  8561. return 'MeshMatcapNodeMaterial';
  8562. }
  8563. constructor( parameters ) {
  8564. super();
  8565. this.lights = false;
  8566. this.isMeshMatcapNodeMaterial = true;
  8567. this.setDefaultValues( _defaultValues$3 );
  8568. this.setValues( parameters );
  8569. }
  8570. setupVariants( builder ) {
  8571. const uv = matcapUV;
  8572. let matcapColor;
  8573. if ( builder.material.matcap ) {
  8574. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  8575. } else {
  8576. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  8577. }
  8578. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  8579. }
  8580. }
  8581. const _defaultValues$2 = /*@__PURE__*/ new PointsMaterial();
  8582. class PointsNodeMaterial extends NodeMaterial {
  8583. static get type() {
  8584. return 'PointsNodeMaterial';
  8585. }
  8586. constructor( parameters ) {
  8587. super();
  8588. this.isPointsNodeMaterial = true;
  8589. this.lights = false;
  8590. this.transparent = true;
  8591. this.sizeNode = null;
  8592. this.setDefaultValues( _defaultValues$2 );
  8593. this.setValues( parameters );
  8594. }
  8595. copy( source ) {
  8596. this.sizeNode = source.sizeNode;
  8597. return super.copy( source );
  8598. }
  8599. }
  8600. class RotateNode extends TempNode {
  8601. static get type() {
  8602. return 'RotateNode';
  8603. }
  8604. constructor( positionNode, rotationNode ) {
  8605. super();
  8606. this.positionNode = positionNode;
  8607. this.rotationNode = rotationNode;
  8608. }
  8609. getNodeType( builder ) {
  8610. return this.positionNode.getNodeType( builder );
  8611. }
  8612. setup( builder ) {
  8613. const { rotationNode, positionNode } = this;
  8614. const nodeType = this.getNodeType( builder );
  8615. if ( nodeType === 'vec2' ) {
  8616. const cosAngle = rotationNode.cos();
  8617. const sinAngle = rotationNode.sin();
  8618. const rotationMatrix = mat2(
  8619. cosAngle, sinAngle,
  8620. sinAngle.negate(), cosAngle
  8621. );
  8622. return rotationMatrix.mul( positionNode );
  8623. } else {
  8624. const rotation = rotationNode;
  8625. 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 ) );
  8626. 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 ) );
  8627. 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 ) );
  8628. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  8629. }
  8630. }
  8631. }
  8632. const rotate = /*@__PURE__*/ nodeProxy( RotateNode );
  8633. const _defaultValues$1 = /*@__PURE__*/ new SpriteMaterial();
  8634. class SpriteNodeMaterial extends NodeMaterial {
  8635. static get type() {
  8636. return 'SpriteNodeMaterial';
  8637. }
  8638. constructor( parameters ) {
  8639. super();
  8640. this.isSpriteNodeMaterial = true;
  8641. this.lights = false;
  8642. this._useSizeAttenuation = true;
  8643. this.positionNode = null;
  8644. this.rotationNode = null;
  8645. this.scaleNode = null;
  8646. this.setDefaultValues( _defaultValues$1 );
  8647. this.setValues( parameters );
  8648. }
  8649. setupPosition( { object, camera, context } ) {
  8650. const sizeAttenuation = this.sizeAttenuation;
  8651. // < VERTEX STAGE >
  8652. const { positionNode, rotationNode, scaleNode } = this;
  8653. const vertex = positionLocal;
  8654. let mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  8655. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  8656. if ( scaleNode !== null ) {
  8657. scale = scale.mul( scaleNode );
  8658. }
  8659. if ( ! sizeAttenuation ) {
  8660. if ( camera.isPerspectiveCamera ) {
  8661. scale = scale.mul( mvPosition.z.negate() );
  8662. } else {
  8663. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  8664. scale = scale.mul( orthoScale.mul( 2 ) );
  8665. }
  8666. }
  8667. let alignedPosition = vertex.xy;
  8668. if ( object.center && object.center.isVector2 === true ) {
  8669. const center = reference$1( 'center', 'vec2' );
  8670. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  8671. }
  8672. alignedPosition = alignedPosition.mul( scale );
  8673. const rotation = float( rotationNode || materialRotation );
  8674. const rotatedPosition = rotate( alignedPosition, rotation );
  8675. mvPosition = vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  8676. const modelViewProjection = cameraProjectionMatrix.mul( mvPosition );
  8677. context.vertex = vertex;
  8678. return modelViewProjection;
  8679. }
  8680. copy( source ) {
  8681. this.positionNode = source.positionNode;
  8682. this.rotationNode = source.rotationNode;
  8683. this.scaleNode = source.scaleNode;
  8684. return super.copy( source );
  8685. }
  8686. get sizeAttenuation() {
  8687. return this._useSizeAttenuation;
  8688. }
  8689. set sizeAttenuation( value ) {
  8690. if ( this._useSizeAttenuation !== value ) {
  8691. this._useSizeAttenuation = value;
  8692. this.needsUpdate = true;
  8693. }
  8694. }
  8695. }
  8696. class ShadowMaskModel extends LightingModel {
  8697. constructor() {
  8698. super();
  8699. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  8700. }
  8701. direct( { shadowMask } ) {
  8702. this.shadowNode.mulAssign( shadowMask );
  8703. }
  8704. finish( context ) {
  8705. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  8706. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  8707. }
  8708. }
  8709. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  8710. class ShadowNodeMaterial extends NodeMaterial {
  8711. static get type() {
  8712. return 'ShadowNodeMaterial';
  8713. }
  8714. constructor( parameters ) {
  8715. super();
  8716. this.isShadowNodeMaterial = true;
  8717. this.lights = true;
  8718. this.setDefaultValues( _defaultValues );
  8719. this.setValues( parameters );
  8720. }
  8721. setupLightingModel( /*builder*/ ) {
  8722. return new ShadowMaskModel();
  8723. }
  8724. }
  8725. const normal = Fn( ( { texture, uv } ) => {
  8726. const epsilon = 0.0001;
  8727. const ret = vec3().toVar();
  8728. If( uv.x.lessThan( epsilon ), () => {
  8729. ret.assign( vec3( 1, 0, 0 ) );
  8730. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  8731. ret.assign( vec3( 0, 1, 0 ) );
  8732. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  8733. ret.assign( vec3( 0, 0, 1 ) );
  8734. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  8735. ret.assign( vec3( - 1, 0, 0 ) );
  8736. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  8737. ret.assign( vec3( 0, - 1, 0 ) );
  8738. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  8739. ret.assign( vec3( 0, 0, - 1 ) );
  8740. } ).Else( () => {
  8741. const step = 0.01;
  8742. 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 );
  8743. 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 );
  8744. 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 );
  8745. ret.assign( vec3( x, y, z ) );
  8746. } );
  8747. return ret.normalize();
  8748. } );
  8749. class Texture3DNode extends TextureNode {
  8750. static get type() {
  8751. return 'Texture3DNode';
  8752. }
  8753. constructor( value, uvNode = null, levelNode = null ) {
  8754. super( value, uvNode, levelNode );
  8755. this.isTexture3DNode = true;
  8756. }
  8757. getInputType( /*builder*/ ) {
  8758. return 'texture3D';
  8759. }
  8760. getDefaultUV() {
  8761. return vec3( 0.5, 0.5, 0.5 );
  8762. }
  8763. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  8764. setupUV( builder, uvNode ) {
  8765. return uvNode;
  8766. }
  8767. generateUV( builder, uvNode ) {
  8768. return uvNode.build( builder, 'vec3' );
  8769. }
  8770. normal( uvNode ) {
  8771. return normal( { texture: this, uv: uvNode } );
  8772. }
  8773. }
  8774. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode );
  8775. class VolumeNodeMaterial extends NodeMaterial {
  8776. static get type() {
  8777. return 'VolumeNodeMaterial';
  8778. }
  8779. constructor( params = {} ) {
  8780. super();
  8781. this.lights = false;
  8782. this.isVolumeNodeMaterial = true;
  8783. this.testNode = null;
  8784. this.setValues( params );
  8785. }
  8786. setup( builder ) {
  8787. const map = texture3D( this.map, null, 0 );
  8788. const hitBox = Fn( ( { orig, dir } ) => {
  8789. const box_min = vec3( - 0.5 );
  8790. const box_max = vec3( 0.5 );
  8791. const inv_dir = dir.reciprocal();
  8792. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  8793. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  8794. const tmin = min$1( tmin_tmp, tmax_tmp );
  8795. const tmax = max$1( tmin_tmp, tmax_tmp );
  8796. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  8797. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  8798. return vec2( t0, t1 );
  8799. } );
  8800. this.fragmentNode = Fn( () => {
  8801. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  8802. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  8803. const rayDir = vDirection.normalize();
  8804. const bounds = vec2( hitBox( { orig: vOrigin, dir: rayDir } ) ).toVar();
  8805. bounds.x.greaterThan( bounds.y ).discard();
  8806. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  8807. const p = vec3( vOrigin.add( bounds.x.mul( rayDir ) ) ).toVar();
  8808. const inc = vec3( rayDir.abs().reciprocal() ).toVar();
  8809. const delta = float( min$1( inc.x, min$1( inc.y, inc.z ) ) ).toVar( 'delta' ); // used 'delta' name in loop
  8810. delta.divAssign( materialReference( 'steps', 'float' ) );
  8811. const ac = vec4( materialReference( 'base', 'color' ), 0.0 ).toVar();
  8812. Loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  8813. const d = property( 'float', 'd' ).assign( map.uv( p.add( 0.5 ) ).r );
  8814. if ( this.testNode !== null ) {
  8815. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  8816. } else {
  8817. // default to show surface of mesh
  8818. ac.a.assign( 1 );
  8819. Break();
  8820. }
  8821. p.addAssign( rayDir.mul( delta ) );
  8822. } );
  8823. ac.a.equal( 0 ).discard();
  8824. return vec4( ac );
  8825. } )();
  8826. super.setup( builder );
  8827. }
  8828. }
  8829. class Animation {
  8830. constructor( nodes, info ) {
  8831. this.nodes = nodes;
  8832. this.info = info;
  8833. this._context = self;
  8834. this._animationLoop = null;
  8835. this._requestId = null;
  8836. }
  8837. start() {
  8838. const update = ( time, frame ) => {
  8839. this._requestId = this._context.requestAnimationFrame( update );
  8840. if ( this.info.autoReset === true ) this.info.reset();
  8841. this.nodes.nodeFrame.update();
  8842. this.info.frame = this.nodes.nodeFrame.frameId;
  8843. if ( this._animationLoop !== null ) this._animationLoop( time, frame );
  8844. };
  8845. update();
  8846. }
  8847. stop() {
  8848. this._context.cancelAnimationFrame( this._requestId );
  8849. this._requestId = null;
  8850. }
  8851. setAnimationLoop( callback ) {
  8852. this._animationLoop = callback;
  8853. }
  8854. setContext( context ) {
  8855. this._context = context;
  8856. }
  8857. dispose() {
  8858. this.stop();
  8859. }
  8860. }
  8861. class ChainMap {
  8862. constructor() {
  8863. this.weakMap = new WeakMap();
  8864. }
  8865. get( keys ) {
  8866. let map = this.weakMap;
  8867. for ( let i = 0; i < keys.length; i ++ ) {
  8868. map = map.get( keys[ i ] );
  8869. if ( map === undefined ) return undefined;
  8870. }
  8871. return map.get( keys[ keys.length - 1 ] );
  8872. }
  8873. set( keys, value ) {
  8874. let map = this.weakMap;
  8875. for ( let i = 0; i < keys.length; i ++ ) {
  8876. const key = keys[ i ];
  8877. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  8878. map = map.get( key );
  8879. }
  8880. return map.set( keys[ keys.length - 1 ], value );
  8881. }
  8882. delete( keys ) {
  8883. let map = this.weakMap;
  8884. for ( let i = 0; i < keys.length; i ++ ) {
  8885. map = map.get( keys[ i ] );
  8886. if ( map === undefined ) return false;
  8887. }
  8888. return map.delete( keys[ keys.length - 1 ] );
  8889. }
  8890. }
  8891. let _id$8 = 0;
  8892. function getKeys( obj ) {
  8893. const keys = Object.keys( obj );
  8894. let proto = Object.getPrototypeOf( obj );
  8895. while ( proto ) {
  8896. const descriptors = Object.getOwnPropertyDescriptors( proto );
  8897. for ( const key in descriptors ) {
  8898. if ( descriptors[ key ] !== undefined ) {
  8899. const descriptor = descriptors[ key ];
  8900. if ( descriptor && typeof descriptor.get === 'function' ) {
  8901. keys.push( key );
  8902. }
  8903. }
  8904. }
  8905. proto = Object.getPrototypeOf( proto );
  8906. }
  8907. return keys;
  8908. }
  8909. class RenderObject {
  8910. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  8911. this._nodes = nodes;
  8912. this._geometries = geometries;
  8913. this.id = _id$8 ++;
  8914. this.renderer = renderer;
  8915. this.object = object;
  8916. this.material = material;
  8917. this.scene = scene;
  8918. this.camera = camera;
  8919. this.lightsNode = lightsNode;
  8920. this.context = renderContext;
  8921. this.geometry = object.geometry;
  8922. this.version = material.version;
  8923. this.drawRange = null;
  8924. this.attributes = null;
  8925. this.pipeline = null;
  8926. this.vertexBuffers = null;
  8927. this.drawParams = null;
  8928. this.bundle = null;
  8929. this.clippingContext = clippingContext;
  8930. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  8931. this.initialNodesCacheKey = this.getDynamicCacheKey();
  8932. this.initialCacheKey = this.getCacheKey();
  8933. this._nodeBuilderState = null;
  8934. this._bindings = null;
  8935. this._monitor = null;
  8936. this.onDispose = null;
  8937. this.isRenderObject = true;
  8938. this.onMaterialDispose = () => {
  8939. this.dispose();
  8940. };
  8941. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  8942. }
  8943. updateClipping( parent ) {
  8944. this.clippingContext = parent;
  8945. }
  8946. get clippingNeedsUpdate() {
  8947. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  8948. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  8949. return true;
  8950. }
  8951. get hardwareClippingPlanes() {
  8952. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  8953. }
  8954. getNodeBuilderState() {
  8955. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  8956. }
  8957. getMonitor() {
  8958. return this._monitor || ( this._monitor = this.getNodeBuilderState().monitor );
  8959. }
  8960. getBindings() {
  8961. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  8962. }
  8963. getIndex() {
  8964. return this._geometries.getIndex( this );
  8965. }
  8966. getIndirect() {
  8967. return this._geometries.getIndirect( this );
  8968. }
  8969. getChainArray() {
  8970. return [ this.object, this.material, this.context, this.lightsNode ];
  8971. }
  8972. setGeometry( geometry ) {
  8973. this.geometry = geometry;
  8974. this.attributes = null;
  8975. }
  8976. getAttributes() {
  8977. if ( this.attributes !== null ) return this.attributes;
  8978. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  8979. const geometry = this.geometry;
  8980. const attributes = [];
  8981. const vertexBuffers = new Set();
  8982. for ( const nodeAttribute of nodeAttributes ) {
  8983. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  8984. if ( attribute === undefined ) continue;
  8985. attributes.push( attribute );
  8986. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  8987. vertexBuffers.add( bufferAttribute );
  8988. }
  8989. this.attributes = attributes;
  8990. this.vertexBuffers = Array.from( vertexBuffers.values() );
  8991. return attributes;
  8992. }
  8993. getVertexBuffers() {
  8994. if ( this.vertexBuffers === null ) this.getAttributes();
  8995. return this.vertexBuffers;
  8996. }
  8997. getDrawParameters() {
  8998. const { object, material, geometry, group, drawRange } = this;
  8999. const drawParams = this.drawParams || ( this.drawParams = {
  9000. vertexCount: 0,
  9001. firstVertex: 0,
  9002. instanceCount: 0,
  9003. firstInstance: 0
  9004. } );
  9005. const index = this.getIndex();
  9006. const hasIndex = ( index !== null );
  9007. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  9008. if ( instanceCount === 0 ) return null;
  9009. drawParams.instanceCount = instanceCount;
  9010. if ( object.isBatchedMesh === true ) return drawParams;
  9011. let rangeFactor = 1;
  9012. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  9013. rangeFactor = 2;
  9014. }
  9015. let firstVertex = drawRange.start * rangeFactor;
  9016. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  9017. if ( group !== null ) {
  9018. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  9019. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  9020. }
  9021. const position = geometry.attributes.position;
  9022. let itemCount = Infinity;
  9023. if ( hasIndex ) {
  9024. itemCount = index.count;
  9025. } else if ( position !== undefined && position !== null ) {
  9026. itemCount = position.count;
  9027. }
  9028. firstVertex = Math.max( firstVertex, 0 );
  9029. lastVertex = Math.min( lastVertex, itemCount );
  9030. const count = lastVertex - firstVertex;
  9031. if ( count < 0 || count === Infinity ) return null;
  9032. drawParams.vertexCount = count;
  9033. drawParams.firstVertex = firstVertex;
  9034. return drawParams;
  9035. }
  9036. getGeometryCacheKey() {
  9037. const { geometry } = this;
  9038. let cacheKey = '';
  9039. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  9040. const attribute = geometry.attributes[ name ];
  9041. cacheKey += name + ',';
  9042. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  9043. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  9044. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  9045. if ( attribute.normalized ) cacheKey += 'n,';
  9046. }
  9047. if ( geometry.index ) {
  9048. cacheKey += 'index,';
  9049. }
  9050. return cacheKey;
  9051. }
  9052. getMaterialCacheKey() {
  9053. const { object, material } = this;
  9054. let cacheKey = material.customProgramCacheKey();
  9055. for ( const property of getKeys( material ) ) {
  9056. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  9057. const value = material[ property ];
  9058. let valueKey;
  9059. if ( value !== null ) {
  9060. // some material values require a formatting
  9061. const type = typeof value;
  9062. if ( type === 'number' ) {
  9063. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  9064. } else if ( type === 'object' ) {
  9065. valueKey = '{';
  9066. if ( value.isTexture ) {
  9067. valueKey += value.mapping;
  9068. }
  9069. valueKey += '}';
  9070. } else {
  9071. valueKey = String( value );
  9072. }
  9073. } else {
  9074. valueKey = String( value );
  9075. }
  9076. cacheKey += /*property + ':' +*/ valueKey + ',';
  9077. }
  9078. cacheKey += this.clippingContextCacheKey + ',';
  9079. if ( object.geometry ) {
  9080. cacheKey += this.getGeometryCacheKey();
  9081. }
  9082. if ( object.skeleton ) {
  9083. cacheKey += object.skeleton.bones.length + ',';
  9084. }
  9085. if ( object.morphTargetInfluences ) {
  9086. cacheKey += object.morphTargetInfluences.length + ',';
  9087. }
  9088. if ( object.isBatchedMesh ) {
  9089. cacheKey += object._matricesTexture.uuid + ',';
  9090. if ( object._colorsTexture !== null ) {
  9091. cacheKey += object._colorsTexture.uuid + ',';
  9092. }
  9093. }
  9094. if ( object.count > 1 ) {
  9095. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  9096. cacheKey += object.uuid + ',';
  9097. }
  9098. cacheKey += object.receiveShadow + ',';
  9099. return hashString( cacheKey );
  9100. }
  9101. get needsGeometryUpdate() {
  9102. return this.geometry.id !== this.object.geometry.id;
  9103. }
  9104. get needsUpdate() {
  9105. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  9106. }
  9107. getDynamicCacheKey() {
  9108. // Environment Nodes Cache Key
  9109. let cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  9110. if ( this.object.receiveShadow ) {
  9111. cacheKey += 1;
  9112. }
  9113. return cacheKey;
  9114. }
  9115. getCacheKey() {
  9116. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  9117. }
  9118. dispose() {
  9119. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  9120. this.onDispose();
  9121. }
  9122. }
  9123. const chainArray = [];
  9124. class RenderObjects {
  9125. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  9126. this.renderer = renderer;
  9127. this.nodes = nodes;
  9128. this.geometries = geometries;
  9129. this.pipelines = pipelines;
  9130. this.bindings = bindings;
  9131. this.info = info;
  9132. this.chainMaps = {};
  9133. }
  9134. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  9135. const chainMap = this.getChainMap( passId );
  9136. // reuse chainArray
  9137. chainArray[ 0 ] = object;
  9138. chainArray[ 1 ] = material;
  9139. chainArray[ 2 ] = renderContext;
  9140. chainArray[ 3 ] = lightsNode;
  9141. let renderObject = chainMap.get( chainArray );
  9142. if ( renderObject === undefined ) {
  9143. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  9144. chainMap.set( chainArray, renderObject );
  9145. } else {
  9146. renderObject.updateClipping( clippingContext );
  9147. if ( renderObject.needsGeometryUpdate ) {
  9148. renderObject.setGeometry( object.geometry );
  9149. }
  9150. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  9151. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  9152. renderObject.dispose();
  9153. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  9154. } else {
  9155. renderObject.version = material.version;
  9156. }
  9157. }
  9158. }
  9159. return renderObject;
  9160. }
  9161. getChainMap( passId = 'default' ) {
  9162. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  9163. }
  9164. dispose() {
  9165. this.chainMaps = {};
  9166. }
  9167. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  9168. const chainMap = this.getChainMap( passId );
  9169. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  9170. renderObject.onDispose = () => {
  9171. this.pipelines.delete( renderObject );
  9172. this.bindings.delete( renderObject );
  9173. this.nodes.delete( renderObject );
  9174. chainMap.delete( renderObject.getChainArray() );
  9175. };
  9176. return renderObject;
  9177. }
  9178. }
  9179. class DataMap {
  9180. constructor() {
  9181. this.data = new WeakMap();
  9182. }
  9183. get( object ) {
  9184. let map = this.data.get( object );
  9185. if ( map === undefined ) {
  9186. map = {};
  9187. this.data.set( object, map );
  9188. }
  9189. return map;
  9190. }
  9191. delete( object ) {
  9192. let map;
  9193. if ( this.data.has( object ) ) {
  9194. map = this.data.get( object );
  9195. this.data.delete( object );
  9196. }
  9197. return map;
  9198. }
  9199. has( object ) {
  9200. return this.data.has( object );
  9201. }
  9202. dispose() {
  9203. this.data = new WeakMap();
  9204. }
  9205. }
  9206. const AttributeType = {
  9207. VERTEX: 1,
  9208. INDEX: 2,
  9209. STORAGE: 3,
  9210. INDIRECT: 4
  9211. };
  9212. // size of a chunk in bytes (STD140 layout)
  9213. const GPU_CHUNK_BYTES = 16;
  9214. // @TODO: Move to src/constants.js
  9215. const BlendColorFactor = 211;
  9216. const OneMinusBlendColorFactor = 212;
  9217. class Attributes extends DataMap {
  9218. constructor( backend ) {
  9219. super();
  9220. this.backend = backend;
  9221. }
  9222. delete( attribute ) {
  9223. const attributeData = super.delete( attribute );
  9224. if ( attributeData !== undefined ) {
  9225. this.backend.destroyAttribute( attribute );
  9226. }
  9227. return attributeData;
  9228. }
  9229. update( attribute, type ) {
  9230. const data = this.get( attribute );
  9231. if ( data.version === undefined ) {
  9232. if ( type === AttributeType.VERTEX ) {
  9233. this.backend.createAttribute( attribute );
  9234. } else if ( type === AttributeType.INDEX ) {
  9235. this.backend.createIndexAttribute( attribute );
  9236. } else if ( type === AttributeType.STORAGE ) {
  9237. this.backend.createStorageAttribute( attribute );
  9238. } else if ( type === AttributeType.INDIRECT ) {
  9239. this.backend.createIndirectStorageAttribute( attribute );
  9240. }
  9241. data.version = this._getBufferAttribute( attribute ).version;
  9242. } else {
  9243. const bufferAttribute = this._getBufferAttribute( attribute );
  9244. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  9245. this.backend.updateAttribute( attribute );
  9246. data.version = bufferAttribute.version;
  9247. }
  9248. }
  9249. }
  9250. _getBufferAttribute( attribute ) {
  9251. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  9252. return attribute;
  9253. }
  9254. }
  9255. function arrayNeedsUint32( array ) {
  9256. // assumes larger values usually on last
  9257. for ( let i = array.length - 1; i >= 0; -- i ) {
  9258. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  9259. }
  9260. return false;
  9261. }
  9262. function getWireframeVersion( geometry ) {
  9263. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  9264. }
  9265. function getWireframeIndex( geometry ) {
  9266. const indices = [];
  9267. const geometryIndex = geometry.index;
  9268. const geometryPosition = geometry.attributes.position;
  9269. if ( geometryIndex !== null ) {
  9270. const array = geometryIndex.array;
  9271. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  9272. const a = array[ i + 0 ];
  9273. const b = array[ i + 1 ];
  9274. const c = array[ i + 2 ];
  9275. indices.push( a, b, b, c, c, a );
  9276. }
  9277. } else {
  9278. const array = geometryPosition.array;
  9279. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  9280. const a = i + 0;
  9281. const b = i + 1;
  9282. const c = i + 2;
  9283. indices.push( a, b, b, c, c, a );
  9284. }
  9285. }
  9286. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  9287. attribute.version = getWireframeVersion( geometry );
  9288. return attribute;
  9289. }
  9290. class Geometries extends DataMap {
  9291. constructor( attributes, info ) {
  9292. super();
  9293. this.attributes = attributes;
  9294. this.info = info;
  9295. this.wireframes = new WeakMap();
  9296. this.attributeCall = new WeakMap();
  9297. }
  9298. has( renderObject ) {
  9299. const geometry = renderObject.geometry;
  9300. return super.has( geometry ) && this.get( geometry ).initialized === true;
  9301. }
  9302. updateForRender( renderObject ) {
  9303. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  9304. this.updateAttributes( renderObject );
  9305. }
  9306. initGeometry( renderObject ) {
  9307. const geometry = renderObject.geometry;
  9308. const geometryData = this.get( geometry );
  9309. geometryData.initialized = true;
  9310. this.info.memory.geometries ++;
  9311. const onDispose = () => {
  9312. this.info.memory.geometries --;
  9313. const index = geometry.index;
  9314. const geometryAttributes = renderObject.getAttributes();
  9315. if ( index !== null ) {
  9316. this.attributes.delete( index );
  9317. }
  9318. for ( const geometryAttribute of geometryAttributes ) {
  9319. this.attributes.delete( geometryAttribute );
  9320. }
  9321. const wireframeAttribute = this.wireframes.get( geometry );
  9322. if ( wireframeAttribute !== undefined ) {
  9323. this.attributes.delete( wireframeAttribute );
  9324. }
  9325. geometry.removeEventListener( 'dispose', onDispose );
  9326. };
  9327. geometry.addEventListener( 'dispose', onDispose );
  9328. }
  9329. updateAttributes( renderObject ) {
  9330. // attributes
  9331. const attributes = renderObject.getAttributes();
  9332. for ( const attribute of attributes ) {
  9333. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  9334. this.updateAttribute( attribute, AttributeType.STORAGE );
  9335. } else {
  9336. this.updateAttribute( attribute, AttributeType.VERTEX );
  9337. }
  9338. }
  9339. // indexes
  9340. const index = this.getIndex( renderObject );
  9341. if ( index !== null ) {
  9342. this.updateAttribute( index, AttributeType.INDEX );
  9343. }
  9344. // indirect
  9345. const indirect = renderObject.geometry.indirect;
  9346. if ( indirect !== null ) {
  9347. this.updateAttribute( indirect, AttributeType.INDIRECT );
  9348. }
  9349. }
  9350. updateAttribute( attribute, type ) {
  9351. const callId = this.info.render.calls;
  9352. if ( ! attribute.isInterleavedBufferAttribute ) {
  9353. if ( this.attributeCall.get( attribute ) !== callId ) {
  9354. this.attributes.update( attribute, type );
  9355. this.attributeCall.set( attribute, callId );
  9356. }
  9357. } else {
  9358. if ( this.attributeCall.get( attribute ) === undefined ) {
  9359. this.attributes.update( attribute, type );
  9360. this.attributeCall.set( attribute, callId );
  9361. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  9362. this.attributes.update( attribute, type );
  9363. this.attributeCall.set( attribute.data, callId );
  9364. this.attributeCall.set( attribute, callId );
  9365. }
  9366. }
  9367. }
  9368. getIndirect( renderObject ) {
  9369. return renderObject.geometry.indirect;
  9370. }
  9371. getIndex( renderObject ) {
  9372. const { geometry, material } = renderObject;
  9373. let index = geometry.index;
  9374. if ( material.wireframe === true ) {
  9375. const wireframes = this.wireframes;
  9376. let wireframeAttribute = wireframes.get( geometry );
  9377. if ( wireframeAttribute === undefined ) {
  9378. wireframeAttribute = getWireframeIndex( geometry );
  9379. wireframes.set( geometry, wireframeAttribute );
  9380. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  9381. this.attributes.delete( wireframeAttribute );
  9382. wireframeAttribute = getWireframeIndex( geometry );
  9383. wireframes.set( geometry, wireframeAttribute );
  9384. }
  9385. index = wireframeAttribute;
  9386. }
  9387. return index;
  9388. }
  9389. }
  9390. class Info {
  9391. constructor() {
  9392. this.autoReset = true;
  9393. this.frame = 0;
  9394. this.calls = 0;
  9395. this.render = {
  9396. calls: 0,
  9397. frameCalls: 0,
  9398. drawCalls: 0,
  9399. triangles: 0,
  9400. points: 0,
  9401. lines: 0,
  9402. timestamp: 0,
  9403. previousFrameCalls: 0,
  9404. timestampCalls: 0
  9405. };
  9406. this.compute = {
  9407. calls: 0,
  9408. frameCalls: 0,
  9409. timestamp: 0,
  9410. previousFrameCalls: 0,
  9411. timestampCalls: 0
  9412. };
  9413. this.memory = {
  9414. geometries: 0,
  9415. textures: 0
  9416. };
  9417. }
  9418. update( object, count, instanceCount ) {
  9419. this.render.drawCalls ++;
  9420. if ( object.isMesh || object.isSprite ) {
  9421. this.render.triangles += instanceCount * ( count / 3 );
  9422. } else if ( object.isPoints ) {
  9423. this.render.points += instanceCount * count;
  9424. } else if ( object.isLineSegments ) {
  9425. this.render.lines += instanceCount * ( count / 2 );
  9426. } else if ( object.isLine ) {
  9427. this.render.lines += instanceCount * ( count - 1 );
  9428. } else {
  9429. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  9430. }
  9431. }
  9432. updateTimestamp( type, time ) {
  9433. if ( this[ type ].timestampCalls === 0 ) {
  9434. this[ type ].timestamp = 0;
  9435. }
  9436. this[ type ].timestamp += time;
  9437. this[ type ].timestampCalls ++;
  9438. if ( this[ type ].timestampCalls >= this[ type ].previousFrameCalls ) {
  9439. this[ type ].timestampCalls = 0;
  9440. }
  9441. }
  9442. reset() {
  9443. const previousRenderFrameCalls = this.render.frameCalls;
  9444. this.render.previousFrameCalls = previousRenderFrameCalls;
  9445. const previousComputeFrameCalls = this.compute.frameCalls;
  9446. this.compute.previousFrameCalls = previousComputeFrameCalls;
  9447. this.render.drawCalls = 0;
  9448. this.render.frameCalls = 0;
  9449. this.compute.frameCalls = 0;
  9450. this.render.triangles = 0;
  9451. this.render.points = 0;
  9452. this.render.lines = 0;
  9453. }
  9454. dispose() {
  9455. this.reset();
  9456. this.calls = 0;
  9457. this.render.calls = 0;
  9458. this.compute.calls = 0;
  9459. this.render.timestamp = 0;
  9460. this.compute.timestamp = 0;
  9461. this.memory.geometries = 0;
  9462. this.memory.textures = 0;
  9463. }
  9464. }
  9465. class Pipeline {
  9466. constructor( cacheKey ) {
  9467. this.cacheKey = cacheKey;
  9468. this.usedTimes = 0;
  9469. }
  9470. }
  9471. class RenderPipeline extends Pipeline {
  9472. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  9473. super( cacheKey );
  9474. this.vertexProgram = vertexProgram;
  9475. this.fragmentProgram = fragmentProgram;
  9476. }
  9477. }
  9478. class ComputePipeline extends Pipeline {
  9479. constructor( cacheKey, computeProgram ) {
  9480. super( cacheKey );
  9481. this.computeProgram = computeProgram;
  9482. this.isComputePipeline = true;
  9483. }
  9484. }
  9485. let _id$7 = 0;
  9486. class ProgrammableStage {
  9487. constructor( code, type, transforms = null, attributes = null ) {
  9488. this.id = _id$7 ++;
  9489. this.code = code;
  9490. this.stage = type;
  9491. this.transforms = transforms;
  9492. this.attributes = attributes;
  9493. this.usedTimes = 0;
  9494. }
  9495. }
  9496. class Pipelines extends DataMap {
  9497. constructor( backend, nodes ) {
  9498. super();
  9499. this.backend = backend;
  9500. this.nodes = nodes;
  9501. this.bindings = null; // set by the bindings
  9502. this.caches = new Map();
  9503. this.programs = {
  9504. vertex: new Map(),
  9505. fragment: new Map(),
  9506. compute: new Map()
  9507. };
  9508. }
  9509. getForCompute( computeNode, bindings ) {
  9510. const { backend } = this;
  9511. const data = this.get( computeNode );
  9512. if ( this._needsComputeUpdate( computeNode ) ) {
  9513. const previousPipeline = data.pipeline;
  9514. if ( previousPipeline ) {
  9515. previousPipeline.usedTimes --;
  9516. previousPipeline.computeProgram.usedTimes --;
  9517. }
  9518. // get shader
  9519. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  9520. // programmable stage
  9521. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  9522. if ( stageCompute === undefined ) {
  9523. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  9524. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  9525. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  9526. backend.createProgram( stageCompute );
  9527. }
  9528. // determine compute pipeline
  9529. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  9530. let pipeline = this.caches.get( cacheKey );
  9531. if ( pipeline === undefined ) {
  9532. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  9533. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  9534. }
  9535. // keep track of all used times
  9536. pipeline.usedTimes ++;
  9537. stageCompute.usedTimes ++;
  9538. //
  9539. data.version = computeNode.version;
  9540. data.pipeline = pipeline;
  9541. }
  9542. return data.pipeline;
  9543. }
  9544. getForRender( renderObject, promises = null ) {
  9545. const { backend } = this;
  9546. const data = this.get( renderObject );
  9547. if ( this._needsRenderUpdate( renderObject ) ) {
  9548. const previousPipeline = data.pipeline;
  9549. if ( previousPipeline ) {
  9550. previousPipeline.usedTimes --;
  9551. previousPipeline.vertexProgram.usedTimes --;
  9552. previousPipeline.fragmentProgram.usedTimes --;
  9553. }
  9554. // get shader
  9555. const nodeBuilderState = renderObject.getNodeBuilderState();
  9556. // programmable stages
  9557. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  9558. if ( stageVertex === undefined ) {
  9559. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  9560. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex' );
  9561. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  9562. backend.createProgram( stageVertex );
  9563. }
  9564. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  9565. if ( stageFragment === undefined ) {
  9566. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  9567. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment' );
  9568. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  9569. backend.createProgram( stageFragment );
  9570. }
  9571. // determine render pipeline
  9572. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  9573. let pipeline = this.caches.get( cacheKey );
  9574. if ( pipeline === undefined ) {
  9575. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  9576. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  9577. } else {
  9578. renderObject.pipeline = pipeline;
  9579. }
  9580. // keep track of all used times
  9581. pipeline.usedTimes ++;
  9582. stageVertex.usedTimes ++;
  9583. stageFragment.usedTimes ++;
  9584. //
  9585. data.pipeline = pipeline;
  9586. }
  9587. return data.pipeline;
  9588. }
  9589. delete( object ) {
  9590. const pipeline = this.get( object ).pipeline;
  9591. if ( pipeline ) {
  9592. // pipeline
  9593. pipeline.usedTimes --;
  9594. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  9595. // programs
  9596. if ( pipeline.isComputePipeline ) {
  9597. pipeline.computeProgram.usedTimes --;
  9598. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  9599. } else {
  9600. pipeline.fragmentProgram.usedTimes --;
  9601. pipeline.vertexProgram.usedTimes --;
  9602. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  9603. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  9604. }
  9605. }
  9606. return super.delete( object );
  9607. }
  9608. dispose() {
  9609. super.dispose();
  9610. this.caches = new Map();
  9611. this.programs = {
  9612. vertex: new Map(),
  9613. fragment: new Map(),
  9614. compute: new Map()
  9615. };
  9616. }
  9617. updateForRender( renderObject ) {
  9618. this.getForRender( renderObject );
  9619. }
  9620. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  9621. // check for existing pipeline
  9622. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  9623. let pipeline = this.caches.get( cacheKey );
  9624. if ( pipeline === undefined ) {
  9625. pipeline = new ComputePipeline( cacheKey, stageCompute );
  9626. this.caches.set( cacheKey, pipeline );
  9627. this.backend.createComputePipeline( pipeline, bindings );
  9628. }
  9629. return pipeline;
  9630. }
  9631. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  9632. // check for existing pipeline
  9633. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  9634. let pipeline = this.caches.get( cacheKey );
  9635. if ( pipeline === undefined ) {
  9636. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  9637. this.caches.set( cacheKey, pipeline );
  9638. renderObject.pipeline = pipeline;
  9639. this.backend.createRenderPipeline( renderObject, promises );
  9640. }
  9641. return pipeline;
  9642. }
  9643. _getComputeCacheKey( computeNode, stageCompute ) {
  9644. return computeNode.id + ',' + stageCompute.id;
  9645. }
  9646. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  9647. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  9648. }
  9649. _releasePipeline( pipeline ) {
  9650. this.caches.delete( pipeline.cacheKey );
  9651. }
  9652. _releaseProgram( program ) {
  9653. const code = program.code;
  9654. const stage = program.stage;
  9655. this.programs[ stage ].delete( code );
  9656. }
  9657. _needsComputeUpdate( computeNode ) {
  9658. const data = this.get( computeNode );
  9659. return data.pipeline === undefined || data.version !== computeNode.version;
  9660. }
  9661. _needsRenderUpdate( renderObject ) {
  9662. const data = this.get( renderObject );
  9663. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  9664. }
  9665. }
  9666. class Bindings extends DataMap {
  9667. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  9668. super();
  9669. this.backend = backend;
  9670. this.textures = textures;
  9671. this.pipelines = pipelines;
  9672. this.attributes = attributes;
  9673. this.nodes = nodes;
  9674. this.info = info;
  9675. this.pipelines.bindings = this; // assign bindings to pipelines
  9676. }
  9677. getForRender( renderObject ) {
  9678. const bindings = renderObject.getBindings();
  9679. for ( const bindGroup of bindings ) {
  9680. const groupData = this.get( bindGroup );
  9681. if ( groupData.bindGroup === undefined ) {
  9682. // each object defines an array of bindings (ubos, textures, samplers etc.)
  9683. this._init( bindGroup );
  9684. this.backend.createBindings( bindGroup, bindings, 0 );
  9685. groupData.bindGroup = bindGroup;
  9686. }
  9687. }
  9688. return bindings;
  9689. }
  9690. getForCompute( computeNode ) {
  9691. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  9692. for ( const bindGroup of bindings ) {
  9693. const groupData = this.get( bindGroup );
  9694. if ( groupData.bindGroup === undefined ) {
  9695. this._init( bindGroup );
  9696. this.backend.createBindings( bindGroup, bindings, 0 );
  9697. groupData.bindGroup = bindGroup;
  9698. }
  9699. }
  9700. return bindings;
  9701. }
  9702. updateForCompute( computeNode ) {
  9703. this._updateBindings( this.getForCompute( computeNode ) );
  9704. }
  9705. updateForRender( renderObject ) {
  9706. this._updateBindings( this.getForRender( renderObject ) );
  9707. }
  9708. _updateBindings( bindings ) {
  9709. for ( const bindGroup of bindings ) {
  9710. this._update( bindGroup, bindings );
  9711. }
  9712. }
  9713. _init( bindGroup ) {
  9714. for ( const binding of bindGroup.bindings ) {
  9715. if ( binding.isSampledTexture ) {
  9716. this.textures.updateTexture( binding.texture );
  9717. } else if ( binding.isStorageBuffer ) {
  9718. const attribute = binding.attribute;
  9719. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  9720. this.attributes.update( attribute, attributeType );
  9721. }
  9722. }
  9723. }
  9724. _update( bindGroup, bindings ) {
  9725. const { backend } = this;
  9726. let needsBindingsUpdate = false;
  9727. let cacheBindings = true;
  9728. let cacheIndex = 0;
  9729. let version = 0;
  9730. // iterate over all bindings and check if buffer updates or a new binding group is required
  9731. for ( const binding of bindGroup.bindings ) {
  9732. if ( binding.isNodeUniformsGroup ) {
  9733. const updated = this.nodes.updateGroup( binding );
  9734. if ( ! updated ) continue;
  9735. }
  9736. if ( binding.isUniformBuffer ) {
  9737. const updated = binding.update();
  9738. if ( updated ) {
  9739. backend.updateBinding( binding );
  9740. }
  9741. } else if ( binding.isSampler ) {
  9742. binding.update();
  9743. } else if ( binding.isSampledTexture ) {
  9744. const texturesTextureData = this.textures.get( binding.texture );
  9745. if ( binding.needsBindingsUpdate( texturesTextureData.generation ) ) needsBindingsUpdate = true;
  9746. const updated = binding.update();
  9747. const texture = binding.texture;
  9748. if ( updated ) {
  9749. this.textures.updateTexture( texture );
  9750. }
  9751. const textureData = backend.get( texture );
  9752. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  9753. cacheBindings = false;
  9754. } else {
  9755. cacheIndex = cacheIndex * 10 + texture.id;
  9756. version += texture.version;
  9757. }
  9758. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  9759. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  9760. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  9761. this.textures.updateTexture( texture );
  9762. needsBindingsUpdate = true;
  9763. }
  9764. if ( texture.isStorageTexture === true ) {
  9765. const textureData = this.get( texture );
  9766. if ( binding.store === true ) {
  9767. textureData.needsMipmap = true;
  9768. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  9769. this.backend.generateMipmaps( texture );
  9770. textureData.needsMipmap = false;
  9771. }
  9772. }
  9773. }
  9774. }
  9775. if ( needsBindingsUpdate === true ) {
  9776. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  9777. }
  9778. }
  9779. }
  9780. function painterSortStable( a, b ) {
  9781. if ( a.groupOrder !== b.groupOrder ) {
  9782. return a.groupOrder - b.groupOrder;
  9783. } else if ( a.renderOrder !== b.renderOrder ) {
  9784. return a.renderOrder - b.renderOrder;
  9785. } else if ( a.material.id !== b.material.id ) {
  9786. return a.material.id - b.material.id;
  9787. } else if ( a.z !== b.z ) {
  9788. return a.z - b.z;
  9789. } else {
  9790. return a.id - b.id;
  9791. }
  9792. }
  9793. function reversePainterSortStable( a, b ) {
  9794. if ( a.groupOrder !== b.groupOrder ) {
  9795. return a.groupOrder - b.groupOrder;
  9796. } else if ( a.renderOrder !== b.renderOrder ) {
  9797. return a.renderOrder - b.renderOrder;
  9798. } else if ( a.z !== b.z ) {
  9799. return b.z - a.z;
  9800. } else {
  9801. return a.id - b.id;
  9802. }
  9803. }
  9804. function needsDoublePass( material ) {
  9805. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  9806. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  9807. }
  9808. class RenderList {
  9809. constructor( lighting, scene, camera ) {
  9810. this.renderItems = [];
  9811. this.renderItemsIndex = 0;
  9812. this.opaque = [];
  9813. this.transparentDoublePass = [];
  9814. this.transparent = [];
  9815. this.bundles = [];
  9816. this.lightsNode = lighting.getNode( scene, camera );
  9817. this.lightsArray = [];
  9818. this.scene = scene;
  9819. this.camera = camera;
  9820. this.occlusionQueryCount = 0;
  9821. }
  9822. begin() {
  9823. this.renderItemsIndex = 0;
  9824. this.opaque.length = 0;
  9825. this.transparentDoublePass.length = 0;
  9826. this.transparent.length = 0;
  9827. this.bundles.length = 0;
  9828. this.lightsArray.length = 0;
  9829. this.occlusionQueryCount = 0;
  9830. return this;
  9831. }
  9832. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  9833. let renderItem = this.renderItems[ this.renderItemsIndex ];
  9834. if ( renderItem === undefined ) {
  9835. renderItem = {
  9836. id: object.id,
  9837. object: object,
  9838. geometry: geometry,
  9839. material: material,
  9840. groupOrder: groupOrder,
  9841. renderOrder: object.renderOrder,
  9842. z: z,
  9843. group: group,
  9844. clippingContext: clippingContext
  9845. };
  9846. this.renderItems[ this.renderItemsIndex ] = renderItem;
  9847. } else {
  9848. renderItem.id = object.id;
  9849. renderItem.object = object;
  9850. renderItem.geometry = geometry;
  9851. renderItem.material = material;
  9852. renderItem.groupOrder = groupOrder;
  9853. renderItem.renderOrder = object.renderOrder;
  9854. renderItem.z = z;
  9855. renderItem.group = group;
  9856. renderItem.clippingContext = clippingContext;
  9857. }
  9858. this.renderItemsIndex ++;
  9859. return renderItem;
  9860. }
  9861. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  9862. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  9863. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  9864. if ( material.transparent === true || material.transmission > 0 ) {
  9865. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  9866. this.transparent.push( renderItem );
  9867. } else {
  9868. this.opaque.push( renderItem );
  9869. }
  9870. }
  9871. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  9872. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  9873. if ( material.transparent === true || material.transmission > 0 ) {
  9874. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  9875. this.transparent.unshift( renderItem );
  9876. } else {
  9877. this.opaque.unshift( renderItem );
  9878. }
  9879. }
  9880. pushBundle( group ) {
  9881. this.bundles.push( group );
  9882. }
  9883. pushLight( light ) {
  9884. this.lightsArray.push( light );
  9885. }
  9886. sort( customOpaqueSort, customTransparentSort ) {
  9887. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  9888. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  9889. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  9890. }
  9891. finish() {
  9892. // update lights
  9893. this.lightsNode.setLights( this.lightsArray );
  9894. // Clear references from inactive renderItems in the list
  9895. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  9896. const renderItem = this.renderItems[ i ];
  9897. if ( renderItem.id === null ) break;
  9898. renderItem.id = null;
  9899. renderItem.object = null;
  9900. renderItem.geometry = null;
  9901. renderItem.material = null;
  9902. renderItem.groupOrder = null;
  9903. renderItem.renderOrder = null;
  9904. renderItem.z = null;
  9905. renderItem.group = null;
  9906. renderItem.clippingContext = null;
  9907. }
  9908. }
  9909. }
  9910. class RenderLists {
  9911. constructor( lighting ) {
  9912. this.lighting = lighting;
  9913. this.lists = new ChainMap();
  9914. }
  9915. get( scene, camera ) {
  9916. const lists = this.lists;
  9917. const keys = [ scene, camera ];
  9918. let list = lists.get( keys );
  9919. if ( list === undefined ) {
  9920. list = new RenderList( this.lighting, scene, camera );
  9921. lists.set( keys, list );
  9922. }
  9923. return list;
  9924. }
  9925. dispose() {
  9926. this.lists = new ChainMap();
  9927. }
  9928. }
  9929. let id = 0;
  9930. class RenderContext {
  9931. constructor() {
  9932. this.id = id ++;
  9933. this.color = true;
  9934. this.clearColor = true;
  9935. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  9936. this.depth = true;
  9937. this.clearDepth = true;
  9938. this.clearDepthValue = 1;
  9939. this.stencil = false;
  9940. this.clearStencil = true;
  9941. this.clearStencilValue = 1;
  9942. this.viewport = false;
  9943. this.viewportValue = new Vector4();
  9944. this.scissor = false;
  9945. this.scissorValue = new Vector4();
  9946. this.textures = null;
  9947. this.depthTexture = null;
  9948. this.activeCubeFace = 0;
  9949. this.sampleCount = 1;
  9950. this.width = 0;
  9951. this.height = 0;
  9952. this.isRenderContext = true;
  9953. }
  9954. getCacheKey() {
  9955. return getCacheKey( this );
  9956. }
  9957. }
  9958. function getCacheKey( renderContext ) {
  9959. const { textures, activeCubeFace } = renderContext;
  9960. const values = [ activeCubeFace ];
  9961. for ( const texture of textures ) {
  9962. values.push( texture.id );
  9963. }
  9964. return hashArray( values );
  9965. }
  9966. class RenderContexts {
  9967. constructor() {
  9968. this.chainMaps = {};
  9969. }
  9970. get( scene, camera, renderTarget = null ) {
  9971. const chainKey = [ scene, camera ];
  9972. let attachmentState;
  9973. if ( renderTarget === null ) {
  9974. attachmentState = 'default';
  9975. } else {
  9976. const format = renderTarget.texture.format;
  9977. const count = renderTarget.textures.length;
  9978. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  9979. }
  9980. const chainMap = this.getChainMap( attachmentState );
  9981. let renderState = chainMap.get( chainKey );
  9982. if ( renderState === undefined ) {
  9983. renderState = new RenderContext();
  9984. chainMap.set( chainKey, renderState );
  9985. }
  9986. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  9987. return renderState;
  9988. }
  9989. getChainMap( attachmentState ) {
  9990. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  9991. }
  9992. dispose() {
  9993. this.chainMaps = {};
  9994. }
  9995. }
  9996. const _size$3 = /*@__PURE__*/ new Vector3();
  9997. class Textures extends DataMap {
  9998. constructor( renderer, backend, info ) {
  9999. super();
  10000. this.renderer = renderer;
  10001. this.backend = backend;
  10002. this.info = info;
  10003. }
  10004. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  10005. const renderTargetData = this.get( renderTarget );
  10006. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  10007. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  10008. const textures = renderTarget.textures;
  10009. const size = this.getSize( textures[ 0 ] );
  10010. const mipWidth = size.width >> activeMipmapLevel;
  10011. const mipHeight = size.height >> activeMipmapLevel;
  10012. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  10013. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  10014. let textureNeedsUpdate = false;
  10015. if ( depthTexture === undefined && useDepthTexture ) {
  10016. depthTexture = new DepthTexture();
  10017. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  10018. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  10019. depthTexture.image.width = mipWidth;
  10020. depthTexture.image.height = mipHeight;
  10021. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  10022. }
  10023. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  10024. textureNeedsUpdate = true;
  10025. if ( depthTexture ) {
  10026. depthTexture.needsUpdate = true;
  10027. depthTexture.image.width = mipWidth;
  10028. depthTexture.image.height = mipHeight;
  10029. }
  10030. }
  10031. renderTargetData.width = size.width;
  10032. renderTargetData.height = size.height;
  10033. renderTargetData.textures = textures;
  10034. renderTargetData.depthTexture = depthTexture || null;
  10035. renderTargetData.depth = renderTarget.depthBuffer;
  10036. renderTargetData.stencil = renderTarget.stencilBuffer;
  10037. renderTargetData.renderTarget = renderTarget;
  10038. if ( renderTargetData.sampleCount !== sampleCount ) {
  10039. textureNeedsUpdate = true;
  10040. if ( depthTexture ) {
  10041. depthTexture.needsUpdate = true;
  10042. }
  10043. renderTargetData.sampleCount = sampleCount;
  10044. }
  10045. //
  10046. const options = { sampleCount };
  10047. for ( let i = 0; i < textures.length; i ++ ) {
  10048. const texture = textures[ i ];
  10049. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  10050. this.updateTexture( texture, options );
  10051. }
  10052. if ( depthTexture ) {
  10053. this.updateTexture( depthTexture, options );
  10054. }
  10055. // dispose handler
  10056. if ( renderTargetData.initialized !== true ) {
  10057. renderTargetData.initialized = true;
  10058. // dispose
  10059. const onDispose = () => {
  10060. renderTarget.removeEventListener( 'dispose', onDispose );
  10061. for ( let i = 0; i < textures.length; i ++ ) {
  10062. this._destroyTexture( textures[ i ] );
  10063. }
  10064. if ( depthTexture ) {
  10065. this._destroyTexture( depthTexture );
  10066. }
  10067. this.delete( renderTarget );
  10068. };
  10069. renderTarget.addEventListener( 'dispose', onDispose );
  10070. }
  10071. }
  10072. updateTexture( texture, options = {} ) {
  10073. const textureData = this.get( texture );
  10074. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  10075. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  10076. const backend = this.backend;
  10077. if ( isRenderTarget && textureData.initialized === true ) {
  10078. // it's an update
  10079. backend.destroySampler( texture );
  10080. backend.destroyTexture( texture );
  10081. }
  10082. //
  10083. if ( texture.isFramebufferTexture ) {
  10084. const renderTarget = this.renderer.getRenderTarget();
  10085. if ( renderTarget ) {
  10086. texture.type = renderTarget.texture.type;
  10087. } else {
  10088. texture.type = UnsignedByteType;
  10089. }
  10090. }
  10091. //
  10092. const { width, height, depth } = this.getSize( texture );
  10093. options.width = width;
  10094. options.height = height;
  10095. options.depth = depth;
  10096. options.needsMipmaps = this.needsMipmaps( texture );
  10097. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  10098. //
  10099. if ( isRenderTarget || texture.isStorageTexture === true ) {
  10100. backend.createSampler( texture );
  10101. backend.createTexture( texture, options );
  10102. textureData.generation = texture.version;
  10103. } else {
  10104. const needsCreate = textureData.initialized !== true;
  10105. if ( needsCreate ) backend.createSampler( texture );
  10106. if ( texture.version > 0 ) {
  10107. const image = texture.image;
  10108. if ( image === undefined ) {
  10109. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  10110. } else if ( image.complete === false ) {
  10111. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  10112. } else {
  10113. if ( texture.images ) {
  10114. const images = [];
  10115. for ( const image of texture.images ) {
  10116. images.push( image );
  10117. }
  10118. options.images = images;
  10119. } else {
  10120. options.image = image;
  10121. }
  10122. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  10123. backend.createTexture( texture, options );
  10124. textureData.isDefaultTexture = false;
  10125. textureData.generation = texture.version;
  10126. }
  10127. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  10128. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  10129. }
  10130. } else {
  10131. // async update
  10132. backend.createDefaultTexture( texture );
  10133. textureData.isDefaultTexture = true;
  10134. textureData.generation = texture.version;
  10135. }
  10136. }
  10137. // dispose handler
  10138. if ( textureData.initialized !== true ) {
  10139. textureData.initialized = true;
  10140. textureData.generation = texture.version;
  10141. //
  10142. this.info.memory.textures ++;
  10143. // dispose
  10144. const onDispose = () => {
  10145. texture.removeEventListener( 'dispose', onDispose );
  10146. this._destroyTexture( texture );
  10147. this.info.memory.textures --;
  10148. };
  10149. texture.addEventListener( 'dispose', onDispose );
  10150. }
  10151. //
  10152. textureData.version = texture.version;
  10153. }
  10154. getSize( texture, target = _size$3 ) {
  10155. let image = texture.images ? texture.images[ 0 ] : texture.image;
  10156. if ( image ) {
  10157. if ( image.image !== undefined ) image = image.image;
  10158. target.width = image.width || 1;
  10159. target.height = image.height || 1;
  10160. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  10161. } else {
  10162. target.width = target.height = target.depth = 1;
  10163. }
  10164. return target;
  10165. }
  10166. getMipLevels( texture, width, height ) {
  10167. let mipLevelCount;
  10168. if ( texture.isCompressedTexture ) {
  10169. if ( texture.mipmaps ) {
  10170. mipLevelCount = texture.mipmaps.length;
  10171. } else {
  10172. mipLevelCount = 1;
  10173. }
  10174. } else {
  10175. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  10176. }
  10177. return mipLevelCount;
  10178. }
  10179. needsMipmaps( texture ) {
  10180. return this.isEnvironmentTexture( texture ) || texture.isCompressedTexture === true || texture.generateMipmaps;
  10181. }
  10182. isEnvironmentTexture( texture ) {
  10183. const mapping = texture.mapping;
  10184. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  10185. }
  10186. _destroyTexture( texture ) {
  10187. this.backend.destroySampler( texture );
  10188. this.backend.destroyTexture( texture );
  10189. this.delete( texture );
  10190. }
  10191. }
  10192. class Color4 extends Color {
  10193. constructor( r, g, b, a = 1 ) {
  10194. super( r, g, b );
  10195. this.a = a;
  10196. }
  10197. set( r, g, b, a = 1 ) {
  10198. this.a = a;
  10199. return super.set( r, g, b );
  10200. }
  10201. copy( color ) {
  10202. if ( color.a !== undefined ) this.a = color.a;
  10203. return super.copy( color );
  10204. }
  10205. clone() {
  10206. return new this.constructor( this.r, this.g, this.b, this.a );
  10207. }
  10208. }
  10209. class ParameterNode extends PropertyNode {
  10210. static get type() {
  10211. return 'ParameterNode';
  10212. }
  10213. constructor( nodeType, name = null ) {
  10214. super( nodeType, name );
  10215. this.isParameterNode = true;
  10216. }
  10217. getHash() {
  10218. return this.uuid;
  10219. }
  10220. generate() {
  10221. return this.name;
  10222. }
  10223. }
  10224. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  10225. class StackNode extends Node {
  10226. static get type() {
  10227. return 'StackNode';
  10228. }
  10229. constructor( parent = null ) {
  10230. super();
  10231. this.nodes = [];
  10232. this.outputNode = null;
  10233. this.parent = parent;
  10234. this._currentCond = null;
  10235. this.isStackNode = true;
  10236. }
  10237. getNodeType( builder ) {
  10238. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  10239. }
  10240. add( node ) {
  10241. this.nodes.push( node );
  10242. return this;
  10243. }
  10244. If( boolNode, method ) {
  10245. const methodNode = new ShaderNode( method );
  10246. this._currentCond = select( boolNode, methodNode );
  10247. return this.add( this._currentCond );
  10248. }
  10249. ElseIf( boolNode, method ) {
  10250. const methodNode = new ShaderNode( method );
  10251. const ifNode = select( boolNode, methodNode );
  10252. this._currentCond.elseNode = ifNode;
  10253. this._currentCond = ifNode;
  10254. return this;
  10255. }
  10256. Else( method ) {
  10257. this._currentCond.elseNode = new ShaderNode( method );
  10258. return this;
  10259. }
  10260. build( builder, ...params ) {
  10261. const previousStack = getCurrentStack();
  10262. setCurrentStack( this );
  10263. for ( const node of this.nodes ) {
  10264. node.build( builder, 'void' );
  10265. }
  10266. setCurrentStack( previousStack );
  10267. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  10268. }
  10269. //
  10270. else( ...params ) { // @deprecated, r168
  10271. console.warn( 'TSL.StackNode: .else() has been renamed to .Else().' );
  10272. return this.Else( ...params );
  10273. }
  10274. elseif( ...params ) { // @deprecated, r168
  10275. console.warn( 'TSL.StackNode: .elseif() has been renamed to .ElseIf().' );
  10276. return this.ElseIf( ...params );
  10277. }
  10278. }
  10279. const stack = /*@__PURE__*/ nodeProxy( StackNode );
  10280. /**
  10281. * This node can be used to define multiple outputs in a shader programs.
  10282. *
  10283. * @augments Node
  10284. */
  10285. class OutputStructNode extends Node {
  10286. static get type() {
  10287. return 'OutputStructNode';
  10288. }
  10289. /**
  10290. * Constructs a new output struct node. The constructor can be invoked with an
  10291. * arbitrary number of nodes representing the members.
  10292. *
  10293. * @param {...Node} members - A parameter list of nodes.
  10294. */
  10295. constructor( ...members ) {
  10296. super();
  10297. /**
  10298. * An array of nodes which defines the output.
  10299. *
  10300. * @type {Array<Node>}
  10301. */
  10302. this.members = members;
  10303. /**
  10304. * This flag can be used for type testing.
  10305. *
  10306. * @type {Boolean}
  10307. * @readonly
  10308. * @default true
  10309. */
  10310. this.isOutputStructNode = true;
  10311. }
  10312. setup( builder ) {
  10313. super.setup( builder );
  10314. const members = this.members;
  10315. const types = [];
  10316. for ( let i = 0; i < members.length; i ++ ) {
  10317. types.push( members[ i ].getNodeType( builder ) );
  10318. }
  10319. this.nodeType = builder.getStructTypeFromNode( this, types ).name;
  10320. }
  10321. generate( builder, output ) {
  10322. const propertyName = builder.getOutputStructName();
  10323. const members = this.members;
  10324. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  10325. for ( let i = 0; i < members.length; i ++ ) {
  10326. const snippet = members[ i ].build( builder, output );
  10327. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  10328. }
  10329. return propertyName;
  10330. }
  10331. }
  10332. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  10333. /**
  10334. * Returns the MRT texture index for the given name.
  10335. *
  10336. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  10337. * @param {String} name - The name of the MRT texture which index is requested.
  10338. * @return {Number} The texture index.
  10339. */
  10340. function getTextureIndex( textures, name ) {
  10341. for ( let i = 0; i < textures.length; i ++ ) {
  10342. if ( textures[ i ].name === name ) {
  10343. return i;
  10344. }
  10345. }
  10346. return - 1;
  10347. }
  10348. /**
  10349. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  10350. * post-processing is shown below:
  10351. * ```js
  10352. * const mrtNode = mrt( {
  10353. * output: output,
  10354. * normal: normalView
  10355. * } ) );
  10356. * ```
  10357. * The MRT output is defined as a dictionary.
  10358. *
  10359. * @augments OutputStructNode
  10360. */
  10361. class MRTNode extends OutputStructNode {
  10362. static get type() {
  10363. return 'MRTNode';
  10364. }
  10365. /**
  10366. * Constructs a new output struct node.
  10367. *
  10368. * @param {Object<String, Node>} outputNodes - The MRT outputs.
  10369. */
  10370. constructor( outputNodes ) {
  10371. super();
  10372. /**
  10373. * A dictionary representing the MRT outputs. The key
  10374. * is the name of the output, the value the node which produces
  10375. * the output result.
  10376. *
  10377. * @type {Object<String, Node>}
  10378. */
  10379. this.outputNodes = outputNodes;
  10380. /**
  10381. * This flag can be used for type testing.
  10382. *
  10383. * @type {Boolean}
  10384. * @readonly
  10385. * @default true
  10386. */
  10387. this.isMRTNode = true;
  10388. }
  10389. /**
  10390. * Returns `true` if the MRT node has an output with the given name.
  10391. *
  10392. * @param {String} name - The name of the output.
  10393. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  10394. */
  10395. has( name ) {
  10396. return this.outputNodes[ name ] !== undefined;
  10397. }
  10398. /**
  10399. * Returns the output node for the given name.
  10400. *
  10401. * @param {String} name - The name of the output.
  10402. * @return {Node} The output node.
  10403. */
  10404. get( name ) {
  10405. return this.outputNodes[ name ];
  10406. }
  10407. /**
  10408. * Merges the outputs of the given MRT node with the outputs of this node.
  10409. *
  10410. * @param {MRTNode} mrtNode - The MRT to merge.
  10411. * @return {MRTNode} A new MRT node with merged outputs..
  10412. */
  10413. merge( mrtNode ) {
  10414. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  10415. return mrt( outputs );
  10416. }
  10417. setup( builder ) {
  10418. const outputNodes = this.outputNodes;
  10419. const mrt = builder.renderer.getRenderTarget();
  10420. const members = [];
  10421. const textures = mrt.textures;
  10422. for ( const name in outputNodes ) {
  10423. const index = getTextureIndex( textures, name );
  10424. members[ index ] = vec4( outputNodes[ name ] );
  10425. }
  10426. this.members = members;
  10427. return super.setup( builder );
  10428. }
  10429. }
  10430. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  10431. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  10432. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  10433. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  10434. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  10435. const result = word.shiftRight( 22 ).bitXor( word );
  10436. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  10437. } );
  10438. // remapping functions https://iquilezles.org/articles/functions/
  10439. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  10440. 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 ) );
  10441. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  10442. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  10443. // https://github.com/cabbibo/glsl-tri-noise-3d
  10444. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  10445. return x.fract().sub( .5 ).abs();
  10446. } ).setLayout( {
  10447. name: 'tri',
  10448. type: 'float',
  10449. inputs: [
  10450. { name: 'x', type: 'float' }
  10451. ]
  10452. } );
  10453. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  10454. 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. ) ) ) ) );
  10455. } ).setLayout( {
  10456. name: 'tri3',
  10457. type: 'vec3',
  10458. inputs: [
  10459. { name: 'p', type: 'vec3' }
  10460. ]
  10461. } );
  10462. const triNoise3D = /*@__PURE__*/ Fn( ( [ p_immutable, spd, time ] ) => {
  10463. const p = vec3( p_immutable ).toVar();
  10464. const z = float( 1.4 ).toVar();
  10465. const rz = float( 0.0 ).toVar();
  10466. const bp = vec3( p ).toVar();
  10467. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  10468. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  10469. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( spd ) ) ) );
  10470. bp.mulAssign( 1.8 );
  10471. z.mulAssign( 1.5 );
  10472. p.mulAssign( 1.2 );
  10473. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  10474. rz.addAssign( t.div( z ) );
  10475. bp.addAssign( 0.14 );
  10476. } );
  10477. return rz;
  10478. } ).setLayout( {
  10479. name: 'triNoise3D',
  10480. type: 'float',
  10481. inputs: [
  10482. { name: 'p', type: 'vec3' },
  10483. { name: 'spd', type: 'float' },
  10484. { name: 'time', type: 'float' }
  10485. ]
  10486. } );
  10487. class FunctionOverloadingNode extends Node {
  10488. static get type() {
  10489. return 'FunctionOverloadingNode';
  10490. }
  10491. constructor( functionNodes = [], ...parametersNodes ) {
  10492. super();
  10493. this.functionNodes = functionNodes;
  10494. this.parametersNodes = parametersNodes;
  10495. this._candidateFnCall = null;
  10496. this.global = true;
  10497. }
  10498. getNodeType() {
  10499. return this.functionNodes[ 0 ].shaderNode.layout.type;
  10500. }
  10501. setup( builder ) {
  10502. const params = this.parametersNodes;
  10503. let candidateFnCall = this._candidateFnCall;
  10504. if ( candidateFnCall === null ) {
  10505. let candidateFn = null;
  10506. let candidateScore = - 1;
  10507. for ( const functionNode of this.functionNodes ) {
  10508. const shaderNode = functionNode.shaderNode;
  10509. const layout = shaderNode.layout;
  10510. if ( layout === null ) {
  10511. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  10512. }
  10513. const inputs = layout.inputs;
  10514. if ( params.length === inputs.length ) {
  10515. let score = 0;
  10516. for ( let i = 0; i < params.length; i ++ ) {
  10517. const param = params[ i ];
  10518. const input = inputs[ i ];
  10519. if ( param.getNodeType( builder ) === input.type ) {
  10520. score ++;
  10521. } else {
  10522. score = 0;
  10523. }
  10524. }
  10525. if ( score > candidateScore ) {
  10526. candidateFn = functionNode;
  10527. candidateScore = score;
  10528. }
  10529. }
  10530. }
  10531. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  10532. }
  10533. return candidateFnCall;
  10534. }
  10535. }
  10536. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  10537. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  10538. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  10539. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  10540. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  10541. // Deprecated
  10542. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  10543. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  10544. return time.mul( timeScale );
  10545. };
  10546. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  10547. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  10548. return time.mul( timeScale );
  10549. };
  10550. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  10551. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  10552. return deltaTime.mul( timeScale );
  10553. };
  10554. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  10555. const oscSquare = ( t = time ) => t.fract().round();
  10556. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  10557. const oscSawtooth = ( t = time ) => t.fract();
  10558. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  10559. return rotate( uv.sub( center ), rotation ).add( center );
  10560. } );
  10561. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  10562. const delta = uv.sub( center );
  10563. const delta2 = delta.dot( delta );
  10564. const delta4 = delta2.mul( delta2 );
  10565. const deltaOffset = delta4.mul( strength );
  10566. return uv.add( delta.mul( deltaOffset ) );
  10567. } );
  10568. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  10569. let worldMatrix;
  10570. if ( position !== null ) {
  10571. worldMatrix = modelWorldMatrix.toVar();
  10572. worldMatrix[ 3 ][ 0 ] = position.x;
  10573. worldMatrix[ 3 ][ 1 ] = position.y;
  10574. worldMatrix[ 3 ][ 2 ] = position.z;
  10575. } else {
  10576. worldMatrix = modelWorldMatrix;
  10577. }
  10578. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  10579. if ( defined( horizontal ) ) {
  10580. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  10581. modelViewMatrix[ 0 ][ 1 ] = 0;
  10582. modelViewMatrix[ 0 ][ 2 ] = 0;
  10583. }
  10584. if ( defined( vertical ) ) {
  10585. modelViewMatrix[ 1 ][ 0 ] = 0;
  10586. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  10587. modelViewMatrix[ 1 ][ 2 ] = 0;
  10588. }
  10589. modelViewMatrix[ 2 ][ 0 ] = 0;
  10590. modelViewMatrix[ 2 ][ 1 ] = 0;
  10591. modelViewMatrix[ 2 ][ 2 ] = 1;
  10592. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  10593. } );
  10594. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  10595. const depth = linearDepth();
  10596. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  10597. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  10598. return finalUV;
  10599. } );
  10600. class SpriteSheetUVNode extends Node {
  10601. static get type() {
  10602. return 'SpriteSheetUVNode';
  10603. }
  10604. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  10605. super( 'vec2' );
  10606. this.countNode = countNode;
  10607. this.uvNode = uvNode;
  10608. this.frameNode = frameNode;
  10609. }
  10610. setup() {
  10611. const { frameNode, uvNode, countNode } = this;
  10612. const { width, height } = countNode;
  10613. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  10614. const column = frameNum.mod( width );
  10615. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  10616. const scale = countNode.reciprocal();
  10617. const uvFrameOffset = vec2( column, row );
  10618. return uvNode.add( uvFrameOffset ).mul( scale );
  10619. }
  10620. }
  10621. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode );
  10622. class TriplanarTexturesNode extends Node {
  10623. static get type() {
  10624. return 'TriplanarTexturesNode';
  10625. }
  10626. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  10627. super( 'vec4' );
  10628. this.textureXNode = textureXNode;
  10629. this.textureYNode = textureYNode;
  10630. this.textureZNode = textureZNode;
  10631. this.scaleNode = scaleNode;
  10632. this.positionNode = positionNode;
  10633. this.normalNode = normalNode;
  10634. }
  10635. setup() {
  10636. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  10637. // Ref: https://github.com/keijiro/StandardTriplanar
  10638. // Blending factor of triplanar mapping
  10639. let bf = normalNode.abs().normalize();
  10640. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  10641. // Triplanar mapping
  10642. const tx = positionNode.yz.mul( scaleNode );
  10643. const ty = positionNode.zx.mul( scaleNode );
  10644. const tz = positionNode.xy.mul( scaleNode );
  10645. // Base color
  10646. const textureX = textureXNode.value;
  10647. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  10648. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  10649. const cx = texture( textureX, tx ).mul( bf.x );
  10650. const cy = texture( textureY, ty ).mul( bf.y );
  10651. const cz = texture( textureZ, tz ).mul( bf.z );
  10652. return add( cx, cy, cz );
  10653. }
  10654. }
  10655. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode );
  10656. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  10657. const _reflectorPlane = new Plane();
  10658. const _normal = new Vector3();
  10659. const _reflectorWorldPosition = new Vector3();
  10660. const _cameraWorldPosition = new Vector3();
  10661. const _rotationMatrix = new Matrix4();
  10662. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  10663. const clipPlane = new Vector4();
  10664. const _view = new Vector3();
  10665. const _target = new Vector3();
  10666. const _q = new Vector4();
  10667. const _size$2 = new Vector2();
  10668. const _defaultRT = new RenderTarget();
  10669. const _defaultUV = screenUV.flipX();
  10670. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  10671. let _inReflector = false;
  10672. class ReflectorNode extends TextureNode {
  10673. static get type() {
  10674. return 'ReflectorNode';
  10675. }
  10676. constructor( parameters = {} ) {
  10677. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  10678. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  10679. this._depthNode = null;
  10680. this.setUpdateMatrix( false );
  10681. }
  10682. get reflector() {
  10683. return this._reflectorBaseNode;
  10684. }
  10685. get target() {
  10686. return this._reflectorBaseNode.target;
  10687. }
  10688. getDepthNode() {
  10689. if ( this._depthNode === null ) {
  10690. if ( this._reflectorBaseNode.depth !== true ) {
  10691. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  10692. }
  10693. this._depthNode = nodeObject( new ReflectorNode( {
  10694. defaultTexture: _defaultRT.depthTexture,
  10695. reflector: this._reflectorBaseNode
  10696. } ) );
  10697. }
  10698. return this._depthNode;
  10699. }
  10700. setup( builder ) {
  10701. // ignore if used in post-processing
  10702. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  10703. return super.setup( builder );
  10704. }
  10705. clone() {
  10706. const texture = new this.constructor( this.reflectorNode );
  10707. texture._reflectorBaseNode = this._reflectorBaseNode;
  10708. return texture;
  10709. }
  10710. }
  10711. class ReflectorBaseNode extends Node {
  10712. static get type() {
  10713. return 'ReflectorBaseNode';
  10714. }
  10715. constructor( textureNode, parameters = {} ) {
  10716. super();
  10717. const {
  10718. target = new Object3D(),
  10719. resolution = 1,
  10720. generateMipmaps = false,
  10721. bounces = true,
  10722. depth = false
  10723. } = parameters;
  10724. //
  10725. this.textureNode = textureNode;
  10726. this.target = target;
  10727. this.resolution = resolution;
  10728. this.generateMipmaps = generateMipmaps;
  10729. this.bounces = bounces;
  10730. this.depth = depth;
  10731. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  10732. this.virtualCameras = new WeakMap();
  10733. this.renderTargets = new WeakMap();
  10734. }
  10735. _updateResolution( renderTarget, renderer ) {
  10736. const resolution = this.resolution;
  10737. renderer.getDrawingBufferSize( _size$2 );
  10738. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  10739. }
  10740. setup( builder ) {
  10741. this._updateResolution( _defaultRT, builder.renderer );
  10742. return super.setup( builder );
  10743. }
  10744. getVirtualCamera( camera ) {
  10745. let virtualCamera = this.virtualCameras.get( camera );
  10746. if ( virtualCamera === undefined ) {
  10747. virtualCamera = camera.clone();
  10748. this.virtualCameras.set( camera, virtualCamera );
  10749. }
  10750. return virtualCamera;
  10751. }
  10752. getRenderTarget( camera ) {
  10753. let renderTarget = this.renderTargets.get( camera );
  10754. if ( renderTarget === undefined ) {
  10755. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  10756. if ( this.generateMipmaps === true ) {
  10757. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  10758. renderTarget.texture.generateMipmaps = true;
  10759. }
  10760. if ( this.depth === true ) {
  10761. renderTarget.depthTexture = new DepthTexture();
  10762. }
  10763. this.renderTargets.set( camera, renderTarget );
  10764. }
  10765. return renderTarget;
  10766. }
  10767. updateBefore( frame ) {
  10768. if ( this.bounces === false && _inReflector ) return;
  10769. _inReflector = true;
  10770. const { scene, camera, renderer, material } = frame;
  10771. const { target } = this;
  10772. const virtualCamera = this.getVirtualCamera( camera );
  10773. const renderTarget = this.getRenderTarget( virtualCamera );
  10774. renderer.getDrawingBufferSize( _size$2 );
  10775. this._updateResolution( renderTarget, renderer );
  10776. //
  10777. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  10778. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  10779. _rotationMatrix.extractRotation( target.matrixWorld );
  10780. _normal.set( 0, 0, 1 );
  10781. _normal.applyMatrix4( _rotationMatrix );
  10782. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  10783. // Avoid rendering when reflector is facing away
  10784. if ( _view.dot( _normal ) > 0 ) return;
  10785. _view.reflect( _normal ).negate();
  10786. _view.add( _reflectorWorldPosition );
  10787. _rotationMatrix.extractRotation( camera.matrixWorld );
  10788. _lookAtPosition.set( 0, 0, - 1 );
  10789. _lookAtPosition.applyMatrix4( _rotationMatrix );
  10790. _lookAtPosition.add( _cameraWorldPosition );
  10791. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  10792. _target.reflect( _normal ).negate();
  10793. _target.add( _reflectorWorldPosition );
  10794. //
  10795. virtualCamera.coordinateSystem = camera.coordinateSystem;
  10796. virtualCamera.position.copy( _view );
  10797. virtualCamera.up.set( 0, 1, 0 );
  10798. virtualCamera.up.applyMatrix4( _rotationMatrix );
  10799. virtualCamera.up.reflect( _normal );
  10800. virtualCamera.lookAt( _target );
  10801. virtualCamera.near = camera.near;
  10802. virtualCamera.far = camera.far;
  10803. virtualCamera.updateMatrixWorld();
  10804. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  10805. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  10806. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  10807. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  10808. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  10809. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  10810. const projectionMatrix = virtualCamera.projectionMatrix;
  10811. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  10812. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  10813. _q.z = - 1.0;
  10814. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  10815. // Calculate the scaled plane vector
  10816. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  10817. const clipBias = 0;
  10818. // Replacing the third row of the projection matrix
  10819. projectionMatrix.elements[ 2 ] = clipPlane.x;
  10820. projectionMatrix.elements[ 6 ] = clipPlane.y;
  10821. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  10822. projectionMatrix.elements[ 14 ] = clipPlane.w;
  10823. //
  10824. this.textureNode.value = renderTarget.texture;
  10825. if ( this.depth === true ) {
  10826. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  10827. }
  10828. material.visible = false;
  10829. const currentRenderTarget = renderer.getRenderTarget();
  10830. const currentMRT = renderer.getMRT();
  10831. renderer.setMRT( null );
  10832. renderer.setRenderTarget( renderTarget );
  10833. renderer.render( scene, virtualCamera );
  10834. renderer.setMRT( currentMRT );
  10835. renderer.setRenderTarget( currentRenderTarget );
  10836. material.visible = true;
  10837. _inReflector = false;
  10838. }
  10839. }
  10840. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  10841. // Helper for passes that need to fill the viewport with a single quad.
  10842. const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  10843. // https://github.com/mrdoob/three.js/pull/21358
  10844. class QuadGeometry extends BufferGeometry {
  10845. constructor( flipY = false ) {
  10846. super();
  10847. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  10848. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  10849. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  10850. }
  10851. }
  10852. const _geometry = /*@__PURE__*/ new QuadGeometry();
  10853. class QuadMesh extends Mesh {
  10854. constructor( material = null ) {
  10855. super( _geometry, material );
  10856. this.camera = _camera;
  10857. this.isQuadMesh = true;
  10858. }
  10859. renderAsync( renderer ) {
  10860. return renderer.renderAsync( this, _camera );
  10861. }
  10862. render( renderer ) {
  10863. renderer.render( this, _camera );
  10864. }
  10865. }
  10866. const _size$1 = /*@__PURE__*/ new Vector2();
  10867. class RTTNode extends TextureNode {
  10868. static get type() {
  10869. return 'RTTNode';
  10870. }
  10871. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  10872. const renderTarget = new RenderTarget( width, height, options );
  10873. super( renderTarget.texture, uv() );
  10874. this.node = node;
  10875. this.width = width;
  10876. this.height = height;
  10877. this.renderTarget = renderTarget;
  10878. this.textureNeedsUpdate = true;
  10879. this.autoUpdate = true;
  10880. this.updateMap = new WeakMap();
  10881. this._rttNode = null;
  10882. this._quadMesh = new QuadMesh( new NodeMaterial() );
  10883. this.updateBeforeType = NodeUpdateType.RENDER;
  10884. }
  10885. get autoSize() {
  10886. return this.width === null;
  10887. }
  10888. setup( builder ) {
  10889. this._rttNode = this.node.context( builder.getSharedContext() );
  10890. this._quadMesh.material.name = 'RTT';
  10891. this._quadMesh.material.needsUpdate = true;
  10892. return super.setup( builder );
  10893. }
  10894. setSize( width, height ) {
  10895. this.width = width;
  10896. this.height = height;
  10897. const effectiveWidth = width * this.pixelRatio;
  10898. const effectiveHeight = height * this.pixelRatio;
  10899. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  10900. this.textureNeedsUpdate = true;
  10901. }
  10902. setPixelRatio( pixelRatio ) {
  10903. this.pixelRatio = pixelRatio;
  10904. this.setSize( this.width, this.height );
  10905. }
  10906. updateBefore( { renderer } ) {
  10907. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  10908. this.textureNeedsUpdate = false;
  10909. //
  10910. if ( this.autoSize === true ) {
  10911. this.pixelRatio = renderer.getPixelRatio();
  10912. const size = renderer.getSize( _size$1 );
  10913. this.setSize( size.width, size.height );
  10914. }
  10915. //
  10916. this._quadMesh.material.fragmentNode = this._rttNode;
  10917. //
  10918. const currentRenderTarget = renderer.getRenderTarget();
  10919. renderer.setRenderTarget( this.renderTarget );
  10920. this._quadMesh.render( renderer );
  10921. renderer.setRenderTarget( currentRenderTarget );
  10922. }
  10923. clone() {
  10924. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  10925. newNode.sampler = this.sampler;
  10926. newNode.referenceNode = this;
  10927. return newNode;
  10928. }
  10929. }
  10930. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  10931. const convertToTexture = ( node, ...params ) => {
  10932. if ( node.isTextureNode ) return node;
  10933. if ( node.isPassNode ) return node.getTextureNode();
  10934. return rtt( node, ...params );
  10935. };
  10936. /** @module PostProcessingUtils **/
  10937. /**
  10938. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  10939. * depth value and the camera's inverse projection matrix.
  10940. *
  10941. * @method
  10942. * @param {vec2} screenPosition - The fragment's screen position expressed as uv coordinates.
  10943. * @param {float} depth - The fragment's depth value.
  10944. * @param {mat4} projectionMatrixInverse - The camera's inverse projection matrix.
  10945. * @return {vec3} The fragments position in view space.
  10946. */
  10947. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  10948. let clipSpacePosition;
  10949. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  10950. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  10951. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  10952. } else {
  10953. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  10954. }
  10955. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  10956. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  10957. } );
  10958. /**
  10959. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  10960. * and the camera's projection matrix
  10961. *
  10962. * @method
  10963. * @param {vec3} viewPosition - The fragments position in view space.
  10964. * @param {mat4} projectionMatrix - The camera's projection matrix.
  10965. * @return {vec2} The fragment's screen position expressed as uv coordinates.
  10966. */
  10967. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  10968. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  10969. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  10970. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  10971. } );
  10972. /**
  10973. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  10974. * target is available or if flat surface normals are required.
  10975. *
  10976. * @method
  10977. * @param {vec2} uv - The texture coordinate.
  10978. * @param {DepthTexture} depthTexture - The depth texture.
  10979. * @param {mat4} projectionMatrixInverse - The camera's inverse projection matrix.
  10980. * @return {vec3} The computed normal vector.
  10981. */
  10982. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  10983. const size = textureSize( textureLoad( depthTexture ) );
  10984. const p = ivec2( uv.mul( size ) ).toVar();
  10985. const c0 = textureLoad( depthTexture, p ).toVar();
  10986. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  10987. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  10988. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  10989. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  10990. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  10991. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  10992. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  10993. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  10994. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  10995. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  10996. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  10997. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  10998. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  10999. const dpdx = dl.lessThan( dr ).select( ce.sub( getViewPosition( uv.sub( vec2( float( 1 ).div( size.x ), 0 ) ), l1, projectionMatrixInverse ) ), ce.negate().add( getViewPosition( uv.add( vec2( float( 1 ).div( size.x ), 0 ) ), r1, projectionMatrixInverse ) ) );
  11000. const dpdy = db.lessThan( dt ).select( ce.sub( getViewPosition( uv.add( vec2( 0, float( 1 ).div( size.y ) ) ), b1, projectionMatrixInverse ) ), ce.negate().add( getViewPosition( uv.sub( vec2( 0, float( 1 ).div( size.y ) ) ), t1, projectionMatrixInverse ) ) );
  11001. return normalize( cross( dpdx, dpdy ) );
  11002. } );
  11003. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  11004. constructor( array, itemSize, typeClass = Float32Array ) {
  11005. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  11006. super( array, itemSize );
  11007. this.isStorageInstancedBufferAttribute = true;
  11008. }
  11009. }
  11010. class StorageBufferAttribute extends BufferAttribute {
  11011. constructor( array, itemSize, typeClass = Float32Array ) {
  11012. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  11013. super( array, itemSize );
  11014. this.isStorageBufferAttribute = true;
  11015. }
  11016. }
  11017. class StorageArrayElementNode extends ArrayElementNode {
  11018. static get type() {
  11019. return 'StorageArrayElementNode';
  11020. }
  11021. constructor( storageBufferNode, indexNode ) {
  11022. super( storageBufferNode, indexNode );
  11023. this.isStorageArrayElementNode = true;
  11024. }
  11025. set storageBufferNode( value ) {
  11026. this.node = value;
  11027. }
  11028. get storageBufferNode() {
  11029. return this.node;
  11030. }
  11031. setup( builder ) {
  11032. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11033. if ( this.node.isPBO === true ) {
  11034. builder.setupPBO( this.node );
  11035. }
  11036. }
  11037. return super.setup( builder );
  11038. }
  11039. generate( builder, output ) {
  11040. let snippet;
  11041. const isAssignContext = builder.context.assign;
  11042. //
  11043. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11044. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  11045. snippet = builder.generatePBO( this );
  11046. } else {
  11047. snippet = this.node.build( builder );
  11048. }
  11049. } else {
  11050. snippet = super.generate( builder );
  11051. }
  11052. if ( isAssignContext !== true ) {
  11053. const type = this.getNodeType( builder );
  11054. snippet = builder.format( snippet, type, output );
  11055. }
  11056. return snippet;
  11057. }
  11058. }
  11059. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode );
  11060. class StorageBufferNode extends BufferNode {
  11061. static get type() {
  11062. return 'StorageBufferNode';
  11063. }
  11064. constructor( value, bufferType = null, bufferCount = 0 ) {
  11065. if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  11066. bufferType = getTypeFromLength( value.itemSize );
  11067. bufferCount = value.count;
  11068. }
  11069. super( value, bufferType, bufferCount );
  11070. this.isStorageBufferNode = true;
  11071. this.access = NodeAccess.READ_WRITE;
  11072. this.isAtomic = false;
  11073. this.isPBO = false;
  11074. this.bufferCount = bufferCount;
  11075. this._attribute = null;
  11076. this._varying = null;
  11077. this.global = true;
  11078. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  11079. // TOOD: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  11080. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  11081. else value.isStorageBufferAttribute = true;
  11082. }
  11083. }
  11084. getHash( builder ) {
  11085. if ( this.bufferCount === 0 ) {
  11086. let bufferData = builder.globalCache.getData( this.value );
  11087. if ( bufferData === undefined ) {
  11088. bufferData = {
  11089. node: this
  11090. };
  11091. builder.globalCache.setData( this.value, bufferData );
  11092. }
  11093. return bufferData.node.uuid;
  11094. }
  11095. return this.uuid;
  11096. }
  11097. getInputType( /*builder*/ ) {
  11098. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  11099. }
  11100. element( indexNode ) {
  11101. return storageElement( this, indexNode );
  11102. }
  11103. setPBO( value ) {
  11104. this.isPBO = value;
  11105. return this;
  11106. }
  11107. getPBO() {
  11108. return this.isPBO;
  11109. }
  11110. setAccess( value ) {
  11111. this.access = value;
  11112. return this;
  11113. }
  11114. toReadOnly() {
  11115. return this.setAccess( NodeAccess.READ_ONLY );
  11116. }
  11117. setAtomic( value ) {
  11118. this.isAtomic = value;
  11119. return this;
  11120. }
  11121. toAtomic() {
  11122. return this.setAtomic( true );
  11123. }
  11124. getAttributeData() {
  11125. if ( this._attribute === null ) {
  11126. this._attribute = bufferAttribute( this.value );
  11127. this._varying = varying( this._attribute );
  11128. }
  11129. return {
  11130. attribute: this._attribute,
  11131. varying: this._varying
  11132. };
  11133. }
  11134. getNodeType( builder ) {
  11135. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  11136. return super.getNodeType( builder );
  11137. }
  11138. const { attribute } = this.getAttributeData();
  11139. return attribute.getNodeType( builder );
  11140. }
  11141. generate( builder ) {
  11142. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  11143. return super.generate( builder );
  11144. }
  11145. const { attribute, varying } = this.getAttributeData();
  11146. const output = varying.build( builder );
  11147. builder.registerTransform( output, attribute );
  11148. return output;
  11149. }
  11150. }
  11151. const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) );
  11152. const storageObject = ( value, type, count ) => { // @deprecated, r171
  11153. console.warn( 'THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  11154. return storage( value, type, count ).setPBO( true );
  11155. };
  11156. const attributeArray = ( count, type = 'float' ) => {
  11157. const itemSize = getLengthFromType( type );
  11158. const buffer = new StorageBufferAttribute( count, itemSize );
  11159. const node = storage( buffer, type, count );
  11160. return node;
  11161. };
  11162. const instancedArray = ( count, type = 'float' ) => {
  11163. const itemSize = getLengthFromType( type );
  11164. const buffer = new StorageInstancedBufferAttribute( count, itemSize );
  11165. const node = storage( buffer, type, count );
  11166. return node;
  11167. };
  11168. class VertexColorNode extends AttributeNode {
  11169. static get type() {
  11170. return 'VertexColorNode';
  11171. }
  11172. constructor( index = 0 ) {
  11173. super( null, 'vec4' );
  11174. this.isVertexColorNode = true;
  11175. this.index = index;
  11176. }
  11177. getAttributeName( /*builder*/ ) {
  11178. const index = this.index;
  11179. return 'color' + ( index > 0 ? index : '' );
  11180. }
  11181. generate( builder ) {
  11182. const attributeName = this.getAttributeName( builder );
  11183. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  11184. let result;
  11185. if ( geometryAttribute === true ) {
  11186. result = super.generate( builder );
  11187. } else {
  11188. // Vertex color fallback should be white
  11189. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  11190. }
  11191. return result;
  11192. }
  11193. serialize( data ) {
  11194. super.serialize( data );
  11195. data.index = this.index;
  11196. }
  11197. deserialize( data ) {
  11198. super.deserialize( data );
  11199. this.index = data.index;
  11200. }
  11201. }
  11202. const vertexColor = ( ...params ) => nodeObject( new VertexColorNode( ...params ) );
  11203. class PointUVNode extends Node {
  11204. static get type() {
  11205. return 'PointUVNode';
  11206. }
  11207. constructor() {
  11208. super( 'vec2' );
  11209. this.isPointUVNode = true;
  11210. }
  11211. generate( /*builder*/ ) {
  11212. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  11213. }
  11214. }
  11215. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  11216. const _e1 = /*@__PURE__*/ new Euler();
  11217. const _m1 = /*@__PURE__*/ new Matrix4();
  11218. class SceneNode extends Node {
  11219. static get type() {
  11220. return 'SceneNode';
  11221. }
  11222. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  11223. super();
  11224. this.scope = scope;
  11225. this.scene = scene;
  11226. }
  11227. setup( builder ) {
  11228. const scope = this.scope;
  11229. const scene = this.scene !== null ? this.scene : builder.scene;
  11230. let output;
  11231. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  11232. output = reference( 'backgroundBlurriness', 'float', scene );
  11233. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  11234. output = reference( 'backgroundIntensity', 'float', scene );
  11235. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  11236. output = uniform( 'mat4' ).label( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  11237. const background = scene.background;
  11238. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  11239. _e1.copy( scene.backgroundRotation );
  11240. // accommodate left-handed frame
  11241. _e1.x *= - 1; _e1.y *= - 1; _e1.z *= - 1;
  11242. _m1.makeRotationFromEuler( _e1 );
  11243. } else {
  11244. _m1.identity();
  11245. }
  11246. return _m1;
  11247. } );
  11248. } else {
  11249. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  11250. }
  11251. return output;
  11252. }
  11253. }
  11254. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  11255. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  11256. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  11257. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  11258. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  11259. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  11260. class StorageTextureNode extends TextureNode {
  11261. static get type() {
  11262. return 'StorageTextureNode';
  11263. }
  11264. constructor( value, uvNode, storeNode = null ) {
  11265. super( value, uvNode );
  11266. this.storeNode = storeNode;
  11267. this.isStorageTextureNode = true;
  11268. this.access = NodeAccess.WRITE_ONLY;
  11269. }
  11270. getInputType( /*builder*/ ) {
  11271. return 'storageTexture';
  11272. }
  11273. setup( builder ) {
  11274. super.setup( builder );
  11275. const properties = builder.getNodeProperties( this );
  11276. properties.storeNode = this.storeNode;
  11277. }
  11278. setAccess( value ) {
  11279. this.access = value;
  11280. return this;
  11281. }
  11282. generate( builder, output ) {
  11283. let snippet;
  11284. if ( this.storeNode !== null ) {
  11285. snippet = this.generateStore( builder );
  11286. } else {
  11287. snippet = super.generate( builder, output );
  11288. }
  11289. return snippet;
  11290. }
  11291. toReadWrite() {
  11292. return this.setAccess( NodeAccess.READ_WRITE );
  11293. }
  11294. toReadOnly() {
  11295. return this.setAccess( NodeAccess.READ_ONLY );
  11296. }
  11297. toWriteOnly() {
  11298. return this.setAccess( NodeAccess.WRITE_ONLY );
  11299. }
  11300. generateStore( builder ) {
  11301. const properties = builder.getNodeProperties( this );
  11302. const { uvNode, storeNode } = properties;
  11303. const textureProperty = super.generate( builder, 'property' );
  11304. const uvSnippet = uvNode.build( builder, 'uvec2' );
  11305. const storeSnippet = storeNode.build( builder, 'vec4' );
  11306. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  11307. builder.addLineFlowCode( snippet, this );
  11308. }
  11309. }
  11310. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode );
  11311. const textureStore = ( value, uvNode, storeNode ) => {
  11312. const node = storageTexture( value, uvNode, storeNode );
  11313. if ( storeNode !== null ) node.append();
  11314. return node;
  11315. };
  11316. class UserDataNode extends ReferenceNode {
  11317. static get type() {
  11318. return 'UserDataNode';
  11319. }
  11320. constructor( property, inputType, userData = null ) {
  11321. super( property, inputType, userData );
  11322. this.userData = userData;
  11323. }
  11324. updateReference( state ) {
  11325. this.reference = this.userData !== null ? this.userData : state.object.userData;
  11326. return this.reference;
  11327. }
  11328. }
  11329. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  11330. const _objectData = new WeakMap();
  11331. class VelocityNode extends TempNode {
  11332. static get type() {
  11333. return 'VelocityNode';
  11334. }
  11335. constructor() {
  11336. super( 'vec2' );
  11337. this.projectionMatrix = null;
  11338. this.updateType = NodeUpdateType.OBJECT;
  11339. this.updateAfterType = NodeUpdateType.OBJECT;
  11340. this.previousModelWorldMatrix = uniform( new Matrix4() );
  11341. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  11342. this.previousCameraViewMatrix = uniform( new Matrix4() );
  11343. }
  11344. setProjectionMatrix( projectionMatrix ) {
  11345. this.projectionMatrix = projectionMatrix;
  11346. }
  11347. update( { frameId, camera, object } ) {
  11348. const previousModelMatrix = getPreviousMatrix( object );
  11349. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  11350. //
  11351. const cameraData = getData( camera );
  11352. if ( cameraData.frameId !== frameId ) {
  11353. cameraData.frameId = frameId;
  11354. if ( cameraData.previousProjectionMatrix === undefined ) {
  11355. cameraData.previousProjectionMatrix = new Matrix4();
  11356. cameraData.previousCameraViewMatrix = new Matrix4();
  11357. cameraData.currentProjectionMatrix = new Matrix4();
  11358. cameraData.currentCameraViewMatrix = new Matrix4();
  11359. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  11360. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  11361. } else {
  11362. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  11363. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  11364. }
  11365. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  11366. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  11367. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  11368. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  11369. }
  11370. }
  11371. updateAfter( { object } ) {
  11372. getPreviousMatrix( object ).copy( object.matrixWorld );
  11373. }
  11374. setup( /*builder*/ ) {
  11375. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  11376. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  11377. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  11378. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  11379. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  11380. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  11381. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  11382. return velocity;
  11383. }
  11384. }
  11385. function getData( object ) {
  11386. let objectData = _objectData.get( object );
  11387. if ( objectData === undefined ) {
  11388. objectData = {};
  11389. _objectData.set( object, objectData );
  11390. }
  11391. return objectData;
  11392. }
  11393. function getPreviousMatrix( object, index = 0 ) {
  11394. const objectData = getData( object );
  11395. let matrix = objectData[ index ];
  11396. if ( matrix === undefined ) {
  11397. objectData[ index ] = matrix = new Matrix4();
  11398. }
  11399. return matrix;
  11400. }
  11401. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  11402. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  11403. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  11404. } ).setLayout( {
  11405. name: 'blendBurn',
  11406. type: 'vec3',
  11407. inputs: [
  11408. { name: 'base', type: 'vec3' },
  11409. { name: 'blend', type: 'vec3' }
  11410. ]
  11411. } );
  11412. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  11413. return min$1( base.div( blend.oneMinus() ), 1.0 );
  11414. } ).setLayout( {
  11415. name: 'blendDodge',
  11416. type: 'vec3',
  11417. inputs: [
  11418. { name: 'base', type: 'vec3' },
  11419. { name: 'blend', type: 'vec3' }
  11420. ]
  11421. } );
  11422. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  11423. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  11424. } ).setLayout( {
  11425. name: 'blendScreen',
  11426. type: 'vec3',
  11427. inputs: [
  11428. { name: 'base', type: 'vec3' },
  11429. { name: 'blend', type: 'vec3' }
  11430. ]
  11431. } );
  11432. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  11433. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  11434. } ).setLayout( {
  11435. name: 'blendOverlay',
  11436. type: 'vec3',
  11437. inputs: [
  11438. { name: 'base', type: 'vec3' },
  11439. { name: 'blend', type: 'vec3' }
  11440. ]
  11441. } );
  11442. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  11443. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  11444. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  11445. } ).setLayout( {
  11446. name: 'blendColor',
  11447. type: 'vec4',
  11448. inputs: [
  11449. { name: 'base', type: 'vec4' },
  11450. { name: 'blend', type: 'vec4' }
  11451. ]
  11452. } );
  11453. // deprecated
  11454. const burn = ( ...params ) => { // @deprecated, r171
  11455. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  11456. return blendBurn( params );
  11457. };
  11458. const dodge = ( ...params ) => { // @deprecated, r171
  11459. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  11460. return blendDodge( params );
  11461. };
  11462. const screen = ( ...params ) => { // @deprecated, r171
  11463. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  11464. return blendScreen( params );
  11465. };
  11466. const overlay = ( ...params ) => { // @deprecated, r171
  11467. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  11468. return blendOverlay( params );
  11469. };
  11470. /** @module ColorAdjustment **/
  11471. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  11472. return luminance( color.rgb );
  11473. } );
  11474. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  11475. return adjustment.mix( luminance( color.rgb ), color.rgb );
  11476. } );
  11477. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  11478. const average = add( color.r, color.g, color.b ).div( 3.0 );
  11479. const mx = color.r.max( color.g.max( color.b ) );
  11480. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  11481. return mix( color.rgb, mx, amt );
  11482. } );
  11483. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  11484. const k = vec3( 0.57735, 0.57735, 0.57735 );
  11485. const cosAngle = adjustment.cos();
  11486. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  11487. } );
  11488. const luminance = (
  11489. color,
  11490. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  11491. ) => dot( color, luminanceCoefficients );
  11492. const threshold = ( color, threshold ) => mix( vec3( 0.0 ), color, luminance( color ).sub( threshold ).max( 0 ) );
  11493. /**
  11494. * Color Decision List (CDL) v1.2
  11495. *
  11496. * Compact representation of color grading information, defined by slope, offset, power, and
  11497. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  11498. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  11499. *
  11500. * @method
  11501. * @param {vec4} color Input (-Infinity < input < +Infinity)
  11502. * @param {number | vec3} slope Slope (0 ≤ slope < +Infinity)
  11503. * @param {number | vec3} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  11504. * @param {number | vec3} power Power (0 < power < +Infinity)
  11505. * @param {number} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  11506. * @param {vec3} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  11507. * @return Output, -Infinity < output < +Infinity
  11508. *
  11509. * References:
  11510. * - ASC CDL v1.2
  11511. * - {@link https://blender.stackexchange.com/a/55239/43930}
  11512. * - {@link https://docs.acescentral.com/specifications/acescc/}
  11513. */
  11514. const cdl = /*@__PURE__*/ Fn( ( [
  11515. color,
  11516. slope = vec3( 1 ),
  11517. offset = vec3( 0 ),
  11518. power = vec3( 1 ),
  11519. saturation = float( 1 ),
  11520. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  11521. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  11522. ] ) => {
  11523. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  11524. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  11525. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  11526. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  11527. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  11528. const pv = v.pow( power ).toVar();
  11529. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  11530. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  11531. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  11532. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  11533. return vec4( v.rgb, color.a );
  11534. } );
  11535. class PosterizeNode extends TempNode {
  11536. static get type() {
  11537. return 'PosterizeNode';
  11538. }
  11539. constructor( sourceNode, stepsNode ) {
  11540. super();
  11541. this.sourceNode = sourceNode;
  11542. this.stepsNode = stepsNode;
  11543. }
  11544. setup() {
  11545. const { sourceNode, stepsNode } = this;
  11546. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  11547. }
  11548. }
  11549. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode );
  11550. const _size = /*@__PURE__*/ new Vector2();
  11551. class PassTextureNode extends TextureNode {
  11552. static get type() {
  11553. return 'PassTextureNode';
  11554. }
  11555. constructor( passNode, texture ) {
  11556. super( texture );
  11557. this.passNode = passNode;
  11558. this.setUpdateMatrix( false );
  11559. }
  11560. setup( builder ) {
  11561. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  11562. return super.setup( builder );
  11563. }
  11564. clone() {
  11565. return new this.constructor( this.passNode, this.value );
  11566. }
  11567. }
  11568. class PassMultipleTextureNode extends PassTextureNode {
  11569. static get type() {
  11570. return 'PassMultipleTextureNode';
  11571. }
  11572. constructor( passNode, textureName, previousTexture = false ) {
  11573. super( passNode, null );
  11574. this.textureName = textureName;
  11575. this.previousTexture = previousTexture;
  11576. }
  11577. updateTexture() {
  11578. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  11579. }
  11580. setup( builder ) {
  11581. this.updateTexture();
  11582. return super.setup( builder );
  11583. }
  11584. clone() {
  11585. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  11586. }
  11587. }
  11588. class PassNode extends TempNode {
  11589. static get type() {
  11590. return 'PassNode';
  11591. }
  11592. constructor( scope, scene, camera, options = {} ) {
  11593. super( 'vec4' );
  11594. this.scope = scope;
  11595. this.scene = scene;
  11596. this.camera = camera;
  11597. this.options = options;
  11598. this._pixelRatio = 1;
  11599. this._width = 1;
  11600. this._height = 1;
  11601. const depthTexture = new DepthTexture();
  11602. depthTexture.isRenderTargetTexture = true;
  11603. //depthTexture.type = FloatType;
  11604. depthTexture.name = 'depth';
  11605. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  11606. renderTarget.texture.name = 'output';
  11607. renderTarget.depthTexture = depthTexture;
  11608. this.renderTarget = renderTarget;
  11609. this.updateBeforeType = NodeUpdateType.FRAME;
  11610. this._textures = {
  11611. output: renderTarget.texture,
  11612. depth: depthTexture
  11613. };
  11614. this._textureNodes = {};
  11615. this._linearDepthNodes = {};
  11616. this._viewZNodes = {};
  11617. this._previousTextures = {};
  11618. this._previousTextureNodes = {};
  11619. this._cameraNear = uniform( 0 );
  11620. this._cameraFar = uniform( 0 );
  11621. this._mrt = null;
  11622. this.isPassNode = true;
  11623. }
  11624. setMRT( mrt ) {
  11625. this._mrt = mrt;
  11626. return this;
  11627. }
  11628. getMRT() {
  11629. return this._mrt;
  11630. }
  11631. isGlobal() {
  11632. return true;
  11633. }
  11634. getTexture( name ) {
  11635. let texture = this._textures[ name ];
  11636. if ( texture === undefined ) {
  11637. const refTexture = this.renderTarget.texture;
  11638. texture = refTexture.clone();
  11639. texture.isRenderTargetTexture = true;
  11640. texture.name = name;
  11641. this._textures[ name ] = texture;
  11642. this.renderTarget.textures.push( texture );
  11643. }
  11644. return texture;
  11645. }
  11646. getPreviousTexture( name ) {
  11647. let texture = this._previousTextures[ name ];
  11648. if ( texture === undefined ) {
  11649. texture = this.getTexture( name ).clone();
  11650. texture.isRenderTargetTexture = true;
  11651. this._previousTextures[ name ] = texture;
  11652. }
  11653. return texture;
  11654. }
  11655. toggleTexture( name ) {
  11656. const prevTexture = this._previousTextures[ name ];
  11657. if ( prevTexture !== undefined ) {
  11658. const texture = this._textures[ name ];
  11659. const index = this.renderTarget.textures.indexOf( texture );
  11660. this.renderTarget.textures[ index ] = prevTexture;
  11661. this._textures[ name ] = prevTexture;
  11662. this._previousTextures[ name ] = texture;
  11663. this._textureNodes[ name ].updateTexture();
  11664. this._previousTextureNodes[ name ].updateTexture();
  11665. }
  11666. }
  11667. getTextureNode( name = 'output' ) {
  11668. let textureNode = this._textureNodes[ name ];
  11669. if ( textureNode === undefined ) {
  11670. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  11671. textureNode.updateTexture();
  11672. this._textureNodes[ name ] = textureNode;
  11673. }
  11674. return textureNode;
  11675. }
  11676. getPreviousTextureNode( name = 'output' ) {
  11677. let textureNode = this._previousTextureNodes[ name ];
  11678. if ( textureNode === undefined ) {
  11679. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  11680. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  11681. textureNode.updateTexture();
  11682. this._previousTextureNodes[ name ] = textureNode;
  11683. }
  11684. return textureNode;
  11685. }
  11686. getViewZNode( name = 'depth' ) {
  11687. let viewZNode = this._viewZNodes[ name ];
  11688. if ( viewZNode === undefined ) {
  11689. const cameraNear = this._cameraNear;
  11690. const cameraFar = this._cameraFar;
  11691. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  11692. }
  11693. return viewZNode;
  11694. }
  11695. getLinearDepthNode( name = 'depth' ) {
  11696. let linearDepthNode = this._linearDepthNodes[ name ];
  11697. if ( linearDepthNode === undefined ) {
  11698. const cameraNear = this._cameraNear;
  11699. const cameraFar = this._cameraFar;
  11700. const viewZNode = this.getViewZNode( name );
  11701. // TODO: just if ( builder.camera.isPerspectiveCamera )
  11702. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  11703. }
  11704. return linearDepthNode;
  11705. }
  11706. setup( { renderer } ) {
  11707. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  11708. // Disable MSAA for WebGL backend for now
  11709. if ( renderer.backend.isWebGLBackend === true ) {
  11710. this.renderTarget.samples = 0;
  11711. }
  11712. this.renderTarget.depthTexture.isMultisampleRenderTargetTexture = this.renderTarget.samples > 1;
  11713. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  11714. }
  11715. updateBefore( frame ) {
  11716. const { renderer } = frame;
  11717. const { scene, camera } = this;
  11718. this._pixelRatio = renderer.getPixelRatio();
  11719. const size = renderer.getSize( _size );
  11720. this.setSize( size.width, size.height );
  11721. const currentRenderTarget = renderer.getRenderTarget();
  11722. const currentMRT = renderer.getMRT();
  11723. this._cameraNear.value = camera.near;
  11724. this._cameraFar.value = camera.far;
  11725. for ( const name in this._previousTextures ) {
  11726. this.toggleTexture( name );
  11727. }
  11728. renderer.setRenderTarget( this.renderTarget );
  11729. renderer.setMRT( this._mrt );
  11730. renderer.render( scene, camera );
  11731. renderer.setRenderTarget( currentRenderTarget );
  11732. renderer.setMRT( currentMRT );
  11733. }
  11734. setSize( width, height ) {
  11735. this._width = width;
  11736. this._height = height;
  11737. const effectiveWidth = this._width * this._pixelRatio;
  11738. const effectiveHeight = this._height * this._pixelRatio;
  11739. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  11740. }
  11741. setPixelRatio( pixelRatio ) {
  11742. this._pixelRatio = pixelRatio;
  11743. this.setSize( this._width, this._height );
  11744. }
  11745. dispose() {
  11746. this.renderTarget.dispose();
  11747. }
  11748. }
  11749. PassNode.COLOR = 'color';
  11750. PassNode.DEPTH = 'depth';
  11751. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  11752. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  11753. const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) );
  11754. class ToonOutlinePassNode extends PassNode {
  11755. static get type() {
  11756. return 'ToonOutlinePassNode';
  11757. }
  11758. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  11759. super( PassNode.COLOR, scene, camera );
  11760. this.colorNode = colorNode;
  11761. this.thicknessNode = thicknessNode;
  11762. this.alphaNode = alphaNode;
  11763. this._materialCache = new WeakMap();
  11764. }
  11765. updateBefore( frame ) {
  11766. const { renderer } = frame;
  11767. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  11768. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  11769. // only render outline for supported materials
  11770. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  11771. if ( material.wireframe === false ) {
  11772. const outlineMaterial = this._getOutlineMaterial( material );
  11773. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  11774. }
  11775. }
  11776. // default
  11777. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  11778. } );
  11779. super.updateBefore( frame );
  11780. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  11781. }
  11782. _createMaterial() {
  11783. const material = new NodeMaterial();
  11784. material.isMeshToonOutlineMaterial = true;
  11785. material.name = 'Toon_Outline';
  11786. material.side = BackSide;
  11787. // vertex node
  11788. const outlineNormal = normalLocal.negate();
  11789. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  11790. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  11791. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  11792. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  11793. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  11794. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  11795. // color node
  11796. material.colorNode = vec4( this.colorNode, this.alphaNode );
  11797. return material;
  11798. }
  11799. _getOutlineMaterial( originalMaterial ) {
  11800. let outlineMaterial = this._materialCache.get( originalMaterial );
  11801. if ( outlineMaterial === undefined ) {
  11802. outlineMaterial = this._createMaterial();
  11803. this._materialCache.set( originalMaterial, outlineMaterial );
  11804. }
  11805. return outlineMaterial;
  11806. }
  11807. }
  11808. 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 ) ) );
  11809. // exposure only
  11810. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  11811. return color.mul( exposure ).clamp();
  11812. } ).setLayout( {
  11813. name: 'linearToneMapping',
  11814. type: 'vec3',
  11815. inputs: [
  11816. { name: 'color', type: 'vec3' },
  11817. { name: 'exposure', type: 'float' }
  11818. ]
  11819. } );
  11820. // source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf
  11821. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  11822. color = color.mul( exposure );
  11823. return color.div( color.add( 1.0 ) ).clamp();
  11824. } ).setLayout( {
  11825. name: 'reinhardToneMapping',
  11826. type: 'vec3',
  11827. inputs: [
  11828. { name: 'color', type: 'vec3' },
  11829. { name: 'exposure', type: 'float' }
  11830. ]
  11831. } );
  11832. // source: http://filmicworlds.com/blog/filmic-tonemapping-operators/
  11833. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  11834. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  11835. color = color.mul( exposure );
  11836. color = color.sub( 0.004 ).max( 0.0 );
  11837. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  11838. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  11839. return a.div( b ).pow( 2.2 );
  11840. } ).setLayout( {
  11841. name: 'cineonToneMapping',
  11842. type: 'vec3',
  11843. inputs: [
  11844. { name: 'color', type: 'vec3' },
  11845. { name: 'exposure', type: 'float' }
  11846. ]
  11847. } );
  11848. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  11849. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  11850. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  11851. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  11852. return a.div( b );
  11853. } );
  11854. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  11855. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  11856. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  11857. const ACESInputMat = mat3(
  11858. 0.59719, 0.35458, 0.04823,
  11859. 0.07600, 0.90834, 0.01566,
  11860. 0.02840, 0.13383, 0.83777
  11861. );
  11862. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  11863. const ACESOutputMat = mat3(
  11864. 1.60475, - 0.53108, - 0.07367,
  11865. - 0.10208, 1.10813, - 0.00605,
  11866. - 0.00327, - 0.07276, 1.07602
  11867. );
  11868. color = color.mul( exposure ).div( 0.6 );
  11869. color = ACESInputMat.mul( color );
  11870. // Apply RRT and ODT
  11871. color = RRTAndODTFit( color );
  11872. color = ACESOutputMat.mul( color );
  11873. // Clamp to [0, 1]
  11874. return color.clamp();
  11875. } ).setLayout( {
  11876. name: 'acesFilmicToneMapping',
  11877. type: 'vec3',
  11878. inputs: [
  11879. { name: 'color', type: 'vec3' },
  11880. { name: 'exposure', type: 'float' }
  11881. ]
  11882. } );
  11883. 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 ) );
  11884. 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 ) );
  11885. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  11886. const x = vec3( x_immutable ).toVar();
  11887. const x2 = vec3( x.mul( x ) ).toVar();
  11888. const x4 = vec3( x2.mul( x2 ) ).toVar();
  11889. 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 ) ) ) );
  11890. } );
  11891. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  11892. const colortone = vec3( color ).toVar();
  11893. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  11894. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  11895. const AgxMinEv = float( - 12.47393 );
  11896. const AgxMaxEv = float( 4.026069 );
  11897. colortone.mulAssign( exposure );
  11898. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  11899. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  11900. colortone.assign( max$1( colortone, 1e-10 ) );
  11901. colortone.assign( log2( colortone ) );
  11902. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  11903. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  11904. colortone.assign( agxDefaultContrastApprox( colortone ) );
  11905. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  11906. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  11907. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  11908. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  11909. return colortone;
  11910. } ).setLayout( {
  11911. name: 'agxToneMapping',
  11912. type: 'vec3',
  11913. inputs: [
  11914. { name: 'color', type: 'vec3' },
  11915. { name: 'exposure', type: 'float' }
  11916. ]
  11917. } );
  11918. // https://modelviewer.dev/examples/tone-mapping
  11919. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  11920. const StartCompression = float( 0.8 - 0.04 );
  11921. const Desaturation = float( 0.15 );
  11922. color = color.mul( exposure );
  11923. const x = min$1( color.r, min$1( color.g, color.b ) );
  11924. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  11925. color.subAssign( offset );
  11926. const peak = max$1( color.r, max$1( color.g, color.b ) );
  11927. If( peak.lessThan( StartCompression ), () => {
  11928. return color;
  11929. } );
  11930. const d = sub( 1, StartCompression );
  11931. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  11932. color.mulAssign( newPeak.div( peak ) );
  11933. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  11934. return mix( color, vec3( newPeak ), g );
  11935. } ).setLayout( {
  11936. name: 'neutralToneMapping',
  11937. type: 'vec3',
  11938. inputs: [
  11939. { name: 'color', type: 'vec3' },
  11940. { name: 'exposure', type: 'float' }
  11941. ]
  11942. } );
  11943. /**
  11944. * This class represents native code sections. It is the base
  11945. * class for modules like {@link FunctionNode} which allows to implement
  11946. * functions with native shader languages.
  11947. *
  11948. * @augments Node
  11949. */
  11950. class CodeNode extends Node {
  11951. static get type() {
  11952. return 'CodeNode';
  11953. }
  11954. /**
  11955. * Constructs a new code node.
  11956. *
  11957. * @param {String} [code=''] - The native code.
  11958. * @param {Array<Node>} [includes=[]] - An array of includes.
  11959. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  11960. */
  11961. constructor( code = '', includes = [], language = '' ) {
  11962. super( 'code' );
  11963. /**
  11964. * This flag can be used for type testing.
  11965. *
  11966. * @type {Boolean}
  11967. * @readonly
  11968. * @default true
  11969. */
  11970. this.isCodeNode = true;
  11971. /**
  11972. * The native code.
  11973. *
  11974. * @type {String}
  11975. * @default ''
  11976. */
  11977. this.code = code;
  11978. /**
  11979. * An array of includes
  11980. *
  11981. * @type {Array<Node>}
  11982. * @default []
  11983. */
  11984. this.includes = includes;
  11985. /**
  11986. * The used language.
  11987. *
  11988. * @type {('js'|'wgsl'|'glsl')}
  11989. * @default ''
  11990. */
  11991. this.language = language;
  11992. }
  11993. /**
  11994. * The method is overwritten so it always returns `true`.
  11995. *
  11996. * @return {Boolean} Whether this node is global or not.
  11997. */
  11998. isGlobal() {
  11999. return true;
  12000. }
  12001. /**
  12002. * Sets the includes of this code node.
  12003. *
  12004. * @param {Array<Node>} includes - The includes to set.
  12005. * @return {CodeNode} A reference to this node.
  12006. */
  12007. setIncludes( includes ) {
  12008. this.includes = includes;
  12009. return this;
  12010. }
  12011. /**
  12012. * Returns the includes of this code node.
  12013. *
  12014. * @param {NodeBuilder} builder - The current node builder.
  12015. * @return {Array<Node>} The includes.
  12016. */
  12017. getIncludes( /*builder*/ ) {
  12018. return this.includes;
  12019. }
  12020. generate( builder ) {
  12021. const includes = this.getIncludes( builder );
  12022. for ( const include of includes ) {
  12023. include.build( builder );
  12024. }
  12025. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  12026. nodeCode.code = this.code;
  12027. return nodeCode.code;
  12028. }
  12029. serialize( data ) {
  12030. super.serialize( data );
  12031. data.code = this.code;
  12032. data.language = this.language;
  12033. }
  12034. deserialize( data ) {
  12035. super.deserialize( data );
  12036. this.code = data.code;
  12037. this.language = data.language;
  12038. }
  12039. }
  12040. const code = /*@__PURE__*/ nodeProxy( CodeNode );
  12041. const js = ( src, includes ) => code( src, includes, 'js' );
  12042. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  12043. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  12044. /**
  12045. * This class represents a native shader function. It can be used to implement
  12046. * certain aspects of a node material with native shader code. There are two predefined
  12047. * TSL functions for easier usage.
  12048. *
  12049. * - `wgslFn`: Creates a WGSL function node.
  12050. * - `glslFn`: Creates a GLSL function node.
  12051. *
  12052. * A basic example with one include looks like so:
  12053. *
  12054. * ```js
  12055. * const desaturateWGSLFn = wgslFn( `
  12056. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  12057. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  12058. * return vec3<f32>( dot( lum, color ) );
  12059. * }`
  12060. *);
  12061. * const someWGSLFn = wgslFn( `
  12062. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  12063. * return desaturate( color );
  12064. * }
  12065. * `, [ desaturateWGSLFn ] );
  12066. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  12067. *```
  12068. * @augments CodeNode
  12069. */
  12070. class FunctionNode extends CodeNode {
  12071. static get type() {
  12072. return 'FunctionNode';
  12073. }
  12074. /**
  12075. * Constructs a new function node.
  12076. *
  12077. * @param {String} [code=''] - The native code.
  12078. * @param {Array<Node>} [includes=[]] - An array of includes.
  12079. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  12080. */
  12081. constructor( code = '', includes = [], language = '' ) {
  12082. super( code, includes, language );
  12083. }
  12084. getNodeType( builder ) {
  12085. return this.getNodeFunction( builder ).type;
  12086. }
  12087. /**
  12088. * Returns the inputs of this function node.
  12089. *
  12090. * @param {NodeBuilder} builder - The current node builder.
  12091. * @return {Array<NodeFunctionInput>} The inputs.
  12092. */
  12093. getInputs( builder ) {
  12094. return this.getNodeFunction( builder ).inputs;
  12095. }
  12096. /**
  12097. * Returns the node function for this function node.
  12098. *
  12099. * @param {NodeBuilder} builder - The current node builder.
  12100. * @return {NodeFunction} The node function.
  12101. */
  12102. getNodeFunction( builder ) {
  12103. const nodeData = builder.getDataFromNode( this );
  12104. let nodeFunction = nodeData.nodeFunction;
  12105. if ( nodeFunction === undefined ) {
  12106. nodeFunction = builder.parser.parseFunction( this.code );
  12107. nodeData.nodeFunction = nodeFunction;
  12108. }
  12109. return nodeFunction;
  12110. }
  12111. generate( builder, output ) {
  12112. super.generate( builder );
  12113. const nodeFunction = this.getNodeFunction( builder );
  12114. const name = nodeFunction.name;
  12115. const type = nodeFunction.type;
  12116. const nodeCode = builder.getCodeFromNode( this, type );
  12117. if ( name !== '' ) {
  12118. // use a custom property name
  12119. nodeCode.name = name;
  12120. }
  12121. const propertyName = builder.getPropertyName( nodeCode );
  12122. const code = this.getNodeFunction( builder ).getCode( propertyName );
  12123. nodeCode.code = code + '\n';
  12124. if ( output === 'property' ) {
  12125. return propertyName;
  12126. } else {
  12127. return builder.format( `${ propertyName }()`, type, output );
  12128. }
  12129. }
  12130. }
  12131. const nativeFn = ( code, includes = [], language = '' ) => {
  12132. for ( let i = 0; i < includes.length; i ++ ) {
  12133. const include = includes[ i ];
  12134. // TSL Function: glslFn, wgslFn
  12135. if ( typeof include === 'function' ) {
  12136. includes[ i ] = include.functionNode;
  12137. }
  12138. }
  12139. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  12140. const fn = ( ...params ) => functionNode.call( ...params );
  12141. fn.functionNode = functionNode;
  12142. return fn;
  12143. };
  12144. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  12145. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  12146. class ScriptableValueNode extends Node {
  12147. static get type() {
  12148. return 'ScriptableValueNode';
  12149. }
  12150. constructor( value = null ) {
  12151. super();
  12152. this._value = value;
  12153. this._cache = null;
  12154. this.inputType = null;
  12155. this.outputType = null;
  12156. this.events = new EventDispatcher();
  12157. this.isScriptableValueNode = true;
  12158. }
  12159. get isScriptableOutputNode() {
  12160. return this.outputType !== null;
  12161. }
  12162. set value( val ) {
  12163. if ( this._value === val ) return;
  12164. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  12165. URL.revokeObjectURL( this._cache );
  12166. this._cache = null;
  12167. }
  12168. this._value = val;
  12169. this.events.dispatchEvent( { type: 'change' } );
  12170. this.refresh();
  12171. }
  12172. get value() {
  12173. return this._value;
  12174. }
  12175. refresh() {
  12176. this.events.dispatchEvent( { type: 'refresh' } );
  12177. }
  12178. getValue() {
  12179. const value = this.value;
  12180. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  12181. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  12182. } else if ( value && value.value !== null && value.value !== undefined && (
  12183. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  12184. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  12185. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  12186. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  12187. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  12188. ( this.inputType === 'Color' && value.value.isColor ) ||
  12189. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  12190. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  12191. ) ) {
  12192. return value.value;
  12193. }
  12194. return this._cache || value;
  12195. }
  12196. getNodeType( builder ) {
  12197. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  12198. }
  12199. setup() {
  12200. return this.value && this.value.isNode ? this.value : float();
  12201. }
  12202. serialize( data ) {
  12203. super.serialize( data );
  12204. if ( this.value !== null ) {
  12205. if ( this.inputType === 'ArrayBuffer' ) {
  12206. data.value = arrayBufferToBase64( this.value );
  12207. } else {
  12208. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  12209. }
  12210. } else {
  12211. data.value = null;
  12212. }
  12213. data.inputType = this.inputType;
  12214. data.outputType = this.outputType;
  12215. }
  12216. deserialize( data ) {
  12217. super.deserialize( data );
  12218. let value = null;
  12219. if ( data.value !== null ) {
  12220. if ( data.inputType === 'ArrayBuffer' ) {
  12221. value = base64ToArrayBuffer( data.value );
  12222. } else if ( data.inputType === 'Texture' ) {
  12223. value = data.meta.textures[ data.value ];
  12224. } else {
  12225. value = data.meta.nodes[ data.value ] || null;
  12226. }
  12227. }
  12228. this.value = value;
  12229. this.inputType = data.inputType;
  12230. this.outputType = data.outputType;
  12231. }
  12232. }
  12233. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode );
  12234. class Resources extends Map {
  12235. get( key, callback = null, ...params ) {
  12236. if ( this.has( key ) ) return super.get( key );
  12237. if ( callback !== null ) {
  12238. const value = callback( ...params );
  12239. this.set( key, value );
  12240. return value;
  12241. }
  12242. }
  12243. }
  12244. class Parameters {
  12245. constructor( scriptableNode ) {
  12246. this.scriptableNode = scriptableNode;
  12247. }
  12248. get parameters() {
  12249. return this.scriptableNode.parameters;
  12250. }
  12251. get layout() {
  12252. return this.scriptableNode.getLayout();
  12253. }
  12254. getInputLayout( id ) {
  12255. return this.scriptableNode.getInputLayout( id );
  12256. }
  12257. get( name ) {
  12258. const param = this.parameters[ name ];
  12259. const value = param ? param.getValue() : null;
  12260. return value;
  12261. }
  12262. }
  12263. const ScriptableNodeResources = new Resources();
  12264. class ScriptableNode extends Node {
  12265. static get type() {
  12266. return 'ScriptableNode';
  12267. }
  12268. constructor( codeNode = null, parameters = {} ) {
  12269. super();
  12270. this.codeNode = codeNode;
  12271. this.parameters = parameters;
  12272. this._local = new Resources();
  12273. this._output = scriptableValue();
  12274. this._outputs = {};
  12275. this._source = this.source;
  12276. this._method = null;
  12277. this._object = null;
  12278. this._value = null;
  12279. this._needsOutputUpdate = true;
  12280. this.onRefresh = this.onRefresh.bind( this );
  12281. this.isScriptableNode = true;
  12282. }
  12283. get source() {
  12284. return this.codeNode ? this.codeNode.code : '';
  12285. }
  12286. setLocal( name, value ) {
  12287. return this._local.set( name, value );
  12288. }
  12289. getLocal( name ) {
  12290. return this._local.get( name );
  12291. }
  12292. onRefresh() {
  12293. this._refresh();
  12294. }
  12295. getInputLayout( id ) {
  12296. for ( const element of this.getLayout() ) {
  12297. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  12298. return element;
  12299. }
  12300. }
  12301. }
  12302. getOutputLayout( id ) {
  12303. for ( const element of this.getLayout() ) {
  12304. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  12305. return element;
  12306. }
  12307. }
  12308. }
  12309. setOutput( name, value ) {
  12310. const outputs = this._outputs;
  12311. if ( outputs[ name ] === undefined ) {
  12312. outputs[ name ] = scriptableValue( value );
  12313. } else {
  12314. outputs[ name ].value = value;
  12315. }
  12316. return this;
  12317. }
  12318. getOutput( name ) {
  12319. return this._outputs[ name ];
  12320. }
  12321. getParameter( name ) {
  12322. return this.parameters[ name ];
  12323. }
  12324. setParameter( name, value ) {
  12325. const parameters = this.parameters;
  12326. if ( value && value.isScriptableNode ) {
  12327. this.deleteParameter( name );
  12328. parameters[ name ] = value;
  12329. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  12330. } else if ( value && value.isScriptableValueNode ) {
  12331. this.deleteParameter( name );
  12332. parameters[ name ] = value;
  12333. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  12334. } else if ( parameters[ name ] === undefined ) {
  12335. parameters[ name ] = scriptableValue( value );
  12336. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  12337. } else {
  12338. parameters[ name ].value = value;
  12339. }
  12340. return this;
  12341. }
  12342. getValue() {
  12343. return this.getDefaultOutput().getValue();
  12344. }
  12345. deleteParameter( name ) {
  12346. let valueNode = this.parameters[ name ];
  12347. if ( valueNode ) {
  12348. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  12349. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  12350. }
  12351. return this;
  12352. }
  12353. clearParameters() {
  12354. for ( const name of Object.keys( this.parameters ) ) {
  12355. this.deleteParameter( name );
  12356. }
  12357. this.needsUpdate = true;
  12358. return this;
  12359. }
  12360. call( name, ...params ) {
  12361. const object = this.getObject();
  12362. const method = object[ name ];
  12363. if ( typeof method === 'function' ) {
  12364. return method( ...params );
  12365. }
  12366. }
  12367. async callAsync( name, ...params ) {
  12368. const object = this.getObject();
  12369. const method = object[ name ];
  12370. if ( typeof method === 'function' ) {
  12371. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  12372. }
  12373. }
  12374. getNodeType( builder ) {
  12375. return this.getDefaultOutputNode().getNodeType( builder );
  12376. }
  12377. refresh( output = null ) {
  12378. if ( output !== null ) {
  12379. this.getOutput( output ).refresh();
  12380. } else {
  12381. this._refresh();
  12382. }
  12383. }
  12384. getObject() {
  12385. if ( this.needsUpdate ) this.dispose();
  12386. if ( this._object !== null ) return this._object;
  12387. //
  12388. const refresh = () => this.refresh();
  12389. const setOutput = ( id, value ) => this.setOutput( id, value );
  12390. const parameters = new Parameters( this );
  12391. const THREE = ScriptableNodeResources.get( 'THREE' );
  12392. const TSL = ScriptableNodeResources.get( 'TSL' );
  12393. const method = this.getMethod( this.codeNode );
  12394. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  12395. this._object = method( ...params );
  12396. const layout = this._object.layout;
  12397. if ( layout ) {
  12398. if ( layout.cache === false ) {
  12399. this._local.clear();
  12400. }
  12401. // default output
  12402. this._output.outputType = layout.outputType || null;
  12403. if ( Array.isArray( layout.elements ) ) {
  12404. for ( const element of layout.elements ) {
  12405. const id = element.id || element.name;
  12406. if ( element.inputType ) {
  12407. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  12408. this.getParameter( id ).inputType = element.inputType;
  12409. }
  12410. if ( element.outputType ) {
  12411. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  12412. this.getOutput( id ).outputType = element.outputType;
  12413. }
  12414. }
  12415. }
  12416. }
  12417. return this._object;
  12418. }
  12419. deserialize( data ) {
  12420. super.deserialize( data );
  12421. for ( const name in this.parameters ) {
  12422. let valueNode = this.parameters[ name ];
  12423. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  12424. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  12425. }
  12426. }
  12427. getLayout() {
  12428. return this.getObject().layout;
  12429. }
  12430. getDefaultOutputNode() {
  12431. const output = this.getDefaultOutput().value;
  12432. if ( output && output.isNode ) {
  12433. return output;
  12434. }
  12435. return float();
  12436. }
  12437. getDefaultOutput() {
  12438. return this._exec()._output;
  12439. }
  12440. getMethod() {
  12441. if ( this.needsUpdate ) this.dispose();
  12442. if ( this._method !== null ) return this._method;
  12443. //
  12444. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  12445. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  12446. const properties = interfaceProps.join( ', ' );
  12447. const declarations = 'var ' + properties + '; var output = {};\n';
  12448. const returns = '\nreturn { ...output, ' + properties + ' };';
  12449. const code = declarations + this.codeNode.code + returns;
  12450. //
  12451. this._method = new Function( ...parametersProps, code );
  12452. return this._method;
  12453. }
  12454. dispose() {
  12455. if ( this._method === null ) return;
  12456. if ( this._object && typeof this._object.dispose === 'function' ) {
  12457. this._object.dispose();
  12458. }
  12459. this._method = null;
  12460. this._object = null;
  12461. this._source = null;
  12462. this._value = null;
  12463. this._needsOutputUpdate = true;
  12464. this._output.value = null;
  12465. this._outputs = {};
  12466. }
  12467. setup() {
  12468. return this.getDefaultOutputNode();
  12469. }
  12470. getCacheKey( force ) {
  12471. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  12472. for ( const param in this.parameters ) {
  12473. values.push( this.parameters[ param ].getCacheKey( force ) );
  12474. }
  12475. return hashArray( values );
  12476. }
  12477. set needsUpdate( value ) {
  12478. if ( value === true ) this.dispose();
  12479. }
  12480. get needsUpdate() {
  12481. return this.source !== this._source;
  12482. }
  12483. _exec() {
  12484. if ( this.codeNode === null ) return this;
  12485. if ( this._needsOutputUpdate === true ) {
  12486. this._value = this.call( 'main' );
  12487. this._needsOutputUpdate = false;
  12488. }
  12489. this._output.value = this._value;
  12490. return this;
  12491. }
  12492. _refresh() {
  12493. this.needsUpdate = true;
  12494. this._exec();
  12495. this._output.refresh();
  12496. }
  12497. }
  12498. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode );
  12499. class FogNode extends Node {
  12500. static get type() {
  12501. return 'FogNode';
  12502. }
  12503. constructor( colorNode, factorNode ) {
  12504. super( 'float' );
  12505. this.isFogNode = true;
  12506. this.colorNode = colorNode;
  12507. this.factorNode = factorNode;
  12508. }
  12509. getViewZNode( builder ) {
  12510. let viewZ;
  12511. const getViewZ = builder.context.getViewZ;
  12512. if ( getViewZ !== undefined ) {
  12513. viewZ = getViewZ( this );
  12514. }
  12515. return ( viewZ || positionView.z ).negate();
  12516. }
  12517. setup() {
  12518. return this.factorNode;
  12519. }
  12520. }
  12521. const fog = /*@__PURE__*/ nodeProxy( FogNode );
  12522. class FogRangeNode extends FogNode {
  12523. static get type() {
  12524. return 'FogRangeNode';
  12525. }
  12526. constructor( colorNode, nearNode, farNode ) {
  12527. super( colorNode );
  12528. this.isFogRangeNode = true;
  12529. this.nearNode = nearNode;
  12530. this.farNode = farNode;
  12531. }
  12532. setup( builder ) {
  12533. const viewZ = this.getViewZNode( builder );
  12534. return smoothstep( this.nearNode, this.farNode, viewZ );
  12535. }
  12536. }
  12537. const rangeFog = /*@__PURE__*/ nodeProxy( FogRangeNode );
  12538. class FogExp2Node extends FogNode {
  12539. static get type() {
  12540. return 'FogExp2Node';
  12541. }
  12542. constructor( colorNode, densityNode ) {
  12543. super( colorNode );
  12544. this.isFogExp2Node = true;
  12545. this.densityNode = densityNode;
  12546. }
  12547. setup( builder ) {
  12548. const viewZ = this.getViewZNode( builder );
  12549. const density = this.densityNode;
  12550. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  12551. }
  12552. }
  12553. const densityFog = /*@__PURE__*/ nodeProxy( FogExp2Node );
  12554. let min = null;
  12555. let max = null;
  12556. class RangeNode extends Node {
  12557. static get type() {
  12558. return 'RangeNode';
  12559. }
  12560. constructor( minNode = float(), maxNode = float() ) {
  12561. super();
  12562. this.minNode = minNode;
  12563. this.maxNode = maxNode;
  12564. }
  12565. getVectorLength( builder ) {
  12566. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  12567. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  12568. return minLength > maxLength ? minLength : maxLength;
  12569. }
  12570. getNodeType( builder ) {
  12571. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  12572. }
  12573. setup( builder ) {
  12574. const object = builder.object;
  12575. let output = null;
  12576. if ( object.count > 1 ) {
  12577. const minValue = this.minNode.value;
  12578. const maxValue = this.maxNode.value;
  12579. const minLength = builder.getTypeLength( getValueType( minValue ) );
  12580. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  12581. min = min || new Vector4();
  12582. max = max || new Vector4();
  12583. min.setScalar( 0 );
  12584. max.setScalar( 0 );
  12585. if ( minLength === 1 ) min.setScalar( minValue );
  12586. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b );
  12587. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  12588. if ( maxLength === 1 ) max.setScalar( maxValue );
  12589. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b );
  12590. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  12591. const stride = 4;
  12592. const length = stride * object.count;
  12593. const array = new Float32Array( length );
  12594. for ( let i = 0; i < length; i ++ ) {
  12595. const index = i % stride;
  12596. const minElementValue = min.getComponent( index );
  12597. const maxElementValue = max.getComponent( index );
  12598. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  12599. }
  12600. const nodeType = this.getNodeType( builder );
  12601. if ( object.count <= 4096 ) {
  12602. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  12603. } else {
  12604. // TODO: Improve anonymous buffer attribute creation removing this part
  12605. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  12606. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  12607. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  12608. }
  12609. } else {
  12610. output = float( 0 );
  12611. }
  12612. return output;
  12613. }
  12614. }
  12615. const range = /*@__PURE__*/ nodeProxy( RangeNode );
  12616. class ComputeBuiltinNode extends Node {
  12617. static get type() {
  12618. return 'ComputeBuiltinNode';
  12619. }
  12620. constructor( builtinName, nodeType ) {
  12621. super( nodeType );
  12622. this._builtinName = builtinName;
  12623. }
  12624. getHash( builder ) {
  12625. return this.getBuiltinName( builder );
  12626. }
  12627. getNodeType( /*builder*/ ) {
  12628. return this.nodeType;
  12629. }
  12630. setBuiltinName( builtinName ) {
  12631. this._builtinName = builtinName;
  12632. return this;
  12633. }
  12634. getBuiltinName( /*builder*/ ) {
  12635. return this._builtinName;
  12636. }
  12637. hasBuiltin( builder ) {
  12638. builder.hasBuiltin( this._builtinName );
  12639. }
  12640. generate( builder, output ) {
  12641. const builtinName = this.getBuiltinName( builder );
  12642. const nodeType = this.getNodeType( builder );
  12643. if ( builder.shaderStage === 'compute' ) {
  12644. return builder.format( builtinName, nodeType, output );
  12645. } else {
  12646. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  12647. return builder.generateConst( nodeType );
  12648. }
  12649. }
  12650. serialize( data ) {
  12651. super.serialize( data );
  12652. data.global = this.global;
  12653. data._builtinName = this._builtinName;
  12654. }
  12655. deserialize( data ) {
  12656. super.deserialize( data );
  12657. this.global = data.global;
  12658. this._builtinName = data._builtinName;
  12659. }
  12660. }
  12661. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  12662. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  12663. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  12664. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  12665. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  12666. class BarrierNode extends Node {
  12667. constructor( scope ) {
  12668. super();
  12669. this.scope = scope;
  12670. }
  12671. generate( builder ) {
  12672. const { scope } = this;
  12673. const { renderer } = builder;
  12674. if ( renderer.backend.isWebGLBackend === true ) {
  12675. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  12676. } else {
  12677. builder.addLineFlowCode( `${scope}Barrier()`, this );
  12678. }
  12679. }
  12680. }
  12681. const barrier = nodeProxy( BarrierNode );
  12682. const workgroupBarrier = () => barrier( 'workgroup' ).append();
  12683. const storageBarrier = () => barrier( 'storage' ).append();
  12684. const textureBarrier = () => barrier( 'texture' ).append();
  12685. class WorkgroupInfoElementNode extends ArrayElementNode {
  12686. constructor( workgroupInfoNode, indexNode ) {
  12687. super( workgroupInfoNode, indexNode );
  12688. this.isWorkgroupInfoElementNode = true;
  12689. }
  12690. generate( builder, output ) {
  12691. let snippet;
  12692. const isAssignContext = builder.context.assign;
  12693. snippet = super.generate( builder );
  12694. if ( isAssignContext !== true ) {
  12695. const type = this.getNodeType( builder );
  12696. snippet = builder.format( snippet, type, output );
  12697. }
  12698. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  12699. return snippet;
  12700. }
  12701. }
  12702. class WorkgroupInfoNode extends Node {
  12703. constructor( scope, bufferType, bufferCount = 0 ) {
  12704. super( bufferType );
  12705. this.bufferType = bufferType;
  12706. this.bufferCount = bufferCount;
  12707. this.isWorkgroupInfoNode = true;
  12708. this.scope = scope;
  12709. }
  12710. label( name ) {
  12711. this.name = name;
  12712. return this;
  12713. }
  12714. getHash() {
  12715. return this.uuid;
  12716. }
  12717. setScope( scope ) {
  12718. this.scope = scope;
  12719. return this;
  12720. }
  12721. getInputType( /*builder*/ ) {
  12722. return `${this.scope}Array`;
  12723. }
  12724. element( indexNode ) {
  12725. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  12726. }
  12727. generate( builder ) {
  12728. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  12729. }
  12730. }
  12731. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  12732. class AtomicFunctionNode extends TempNode {
  12733. static get type() {
  12734. return 'AtomicFunctionNode';
  12735. }
  12736. constructor( method, pointerNode, valueNode, storeNode = null ) {
  12737. super( 'uint' );
  12738. this.method = method;
  12739. this.pointerNode = pointerNode;
  12740. this.valueNode = valueNode;
  12741. this.storeNode = storeNode;
  12742. }
  12743. getInputType( builder ) {
  12744. return this.pointerNode.getNodeType( builder );
  12745. }
  12746. getNodeType( builder ) {
  12747. return this.getInputType( builder );
  12748. }
  12749. generate( builder ) {
  12750. const method = this.method;
  12751. const type = this.getNodeType( builder );
  12752. const inputType = this.getInputType( builder );
  12753. const a = this.pointerNode;
  12754. const b = this.valueNode;
  12755. const params = [];
  12756. params.push( `&${ a.build( builder, inputType ) }` );
  12757. params.push( b.build( builder, inputType ) );
  12758. const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`;
  12759. if ( this.storeNode !== null ) {
  12760. const varSnippet = this.storeNode.build( builder, inputType );
  12761. builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}`, this );
  12762. } else {
  12763. builder.addLineFlowCode( methodSnippet, this );
  12764. }
  12765. }
  12766. }
  12767. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  12768. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  12769. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  12770. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  12771. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  12772. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  12773. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  12774. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  12775. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  12776. const atomicNode = nodeProxy( AtomicFunctionNode );
  12777. const atomicFunc = ( method, pointerNode, valueNode, storeNode ) => {
  12778. const node = atomicNode( method, pointerNode, valueNode, storeNode );
  12779. node.append();
  12780. return node;
  12781. };
  12782. const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode );
  12783. const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode );
  12784. const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode );
  12785. const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode );
  12786. const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode );
  12787. const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode );
  12788. const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode );
  12789. const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode );
  12790. let uniformsLib;
  12791. function getLightData( light ) {
  12792. uniformsLib = uniformsLib || new WeakMap();
  12793. let uniforms = uniformsLib.get( light );
  12794. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  12795. return uniforms;
  12796. }
  12797. function lightShadowMatrix( light ) {
  12798. const data = getLightData( light );
  12799. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( () => {
  12800. light.shadow.updateMatrices( light );
  12801. return light.shadow.matrix;
  12802. } ) );
  12803. }
  12804. function lightProjectionUV( light ) {
  12805. const data = getLightData( light );
  12806. if ( data.projectionUV === undefined ) {
  12807. const spotLightCoord = lightShadowMatrix( light ).mul( positionWorld );
  12808. data.projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  12809. }
  12810. return data.projectionUV;
  12811. }
  12812. function lightPosition( light ) {
  12813. const data = getLightData( light );
  12814. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  12815. }
  12816. function lightTargetPosition( light ) {
  12817. const data = getLightData( light );
  12818. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  12819. }
  12820. function lightViewPosition( light ) {
  12821. const data = getLightData( light );
  12822. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  12823. self.value = self.value || new Vector3();
  12824. self.value.setFromMatrixPosition( light.matrixWorld );
  12825. self.value.applyMatrix4( camera.matrixWorldInverse );
  12826. } ) );
  12827. }
  12828. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  12829. const sortLights = ( lights ) => {
  12830. return lights.sort( ( a, b ) => a.id - b.id );
  12831. };
  12832. const getLightNodeById = ( id, lightNodes ) => {
  12833. for ( const lightNode of lightNodes ) {
  12834. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  12835. return lightNode;
  12836. }
  12837. }
  12838. return null;
  12839. };
  12840. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  12841. class LightsNode extends Node {
  12842. static get type() {
  12843. return 'LightsNode';
  12844. }
  12845. constructor() {
  12846. super( 'vec3' );
  12847. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  12848. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  12849. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  12850. this._lights = [];
  12851. this._lightNodes = null;
  12852. this._lightNodesHash = null;
  12853. this.global = true;
  12854. }
  12855. getHash( builder ) {
  12856. if ( this._lightNodesHash === null ) {
  12857. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  12858. const hash = [];
  12859. for ( const lightNode of this._lightNodes ) {
  12860. hash.push( lightNode.getSelf().getHash() );
  12861. }
  12862. this._lightNodesHash = 'lights-' + hash.join( ',' );
  12863. }
  12864. return this._lightNodesHash;
  12865. }
  12866. analyze( builder ) {
  12867. const properties = builder.getDataFromNode( this );
  12868. for ( const node of properties.nodes ) {
  12869. node.build( builder );
  12870. }
  12871. }
  12872. setupLightsNode( builder ) {
  12873. const lightNodes = [];
  12874. const previousLightNodes = this._lightNodes;
  12875. const lights = sortLights( this._lights );
  12876. const nodeLibrary = builder.renderer.library;
  12877. for ( const light of lights ) {
  12878. if ( light.isNode ) {
  12879. lightNodes.push( nodeObject( light ) );
  12880. } else {
  12881. let lightNode = null;
  12882. if ( previousLightNodes !== null ) {
  12883. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  12884. }
  12885. if ( lightNode === null ) {
  12886. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  12887. if ( lightNodeClass === null ) {
  12888. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  12889. continue;
  12890. }
  12891. let lightNode = null;
  12892. if ( ! _lightsNodeRef.has( light ) ) {
  12893. lightNode = nodeObject( new lightNodeClass( light ) );
  12894. _lightsNodeRef.set( light, lightNode );
  12895. } else {
  12896. lightNode = _lightsNodeRef.get( light );
  12897. }
  12898. lightNodes.push( lightNode );
  12899. }
  12900. }
  12901. }
  12902. this._lightNodes = lightNodes;
  12903. }
  12904. setupLights( builder, lightNodes ) {
  12905. for ( const lightNode of lightNodes ) {
  12906. lightNode.build( builder );
  12907. }
  12908. }
  12909. setup( builder ) {
  12910. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  12911. const context = builder.context;
  12912. const lightingModel = context.lightingModel;
  12913. let outgoingLightNode = this.outgoingLightNode;
  12914. if ( lightingModel ) {
  12915. const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  12916. context.outgoingLight = outgoingLightNode;
  12917. const stack = builder.addStack();
  12918. //
  12919. const properties = builder.getDataFromNode( this );
  12920. properties.nodes = stack.nodes;
  12921. //
  12922. lightingModel.start( context, stack, builder );
  12923. // lights
  12924. this.setupLights( builder, _lightNodes );
  12925. //
  12926. lightingModel.indirect( context, stack, builder );
  12927. //
  12928. const { backdrop, backdropAlpha } = context;
  12929. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  12930. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  12931. if ( backdrop !== null ) {
  12932. if ( backdropAlpha !== null ) {
  12933. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  12934. } else {
  12935. totalDiffuse = vec3( backdrop );
  12936. }
  12937. context.material.transparent = true;
  12938. }
  12939. totalDiffuseNode.assign( totalDiffuse );
  12940. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  12941. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  12942. //
  12943. lightingModel.finish( context, stack, builder );
  12944. //
  12945. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  12946. }
  12947. return outgoingLightNode;
  12948. }
  12949. setLights( lights ) {
  12950. this._lights = lights;
  12951. this._lightNodes = null;
  12952. this._lightNodesHash = null;
  12953. return this;
  12954. }
  12955. getLights() {
  12956. return this._lights;
  12957. }
  12958. get hasLights() {
  12959. return this._lights.length > 0;
  12960. }
  12961. }
  12962. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  12963. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  12964. const shadowWorldPosition = /*@__PURE__*/ vec3().toVar( 'shadowWorldPosition' );
  12965. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  12966. let dist = positionWorld.sub( position ).length();
  12967. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  12968. dist = dist.saturate(); // clamp to [ 0, 1 ]
  12969. return dist;
  12970. } );
  12971. const linearShadowDistance = ( light ) => {
  12972. const camera = light.shadow.camera;
  12973. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  12974. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  12975. const referencePosition = objectPosition( light );
  12976. return linearDistance( referencePosition, nearDistance, farDistance );
  12977. };
  12978. const getShadowMaterial = ( light ) => {
  12979. let material = shadowMaterialLib.get( light );
  12980. if ( material === undefined ) {
  12981. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  12982. material = new NodeMaterial();
  12983. material.colorNode = vec4( 0, 0, 0, 1 );
  12984. material.depthNode = depthNode;
  12985. material.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  12986. material.blending = NoBlending;
  12987. material.name = 'ShadowMaterial';
  12988. shadowMaterialLib.set( light, material );
  12989. }
  12990. return material;
  12991. };
  12992. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  12993. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  12994. } );
  12995. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  12996. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  12997. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  12998. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  12999. const texelSize = vec2( 1 ).div( mapSize );
  13000. const dx0 = texelSize.x.negate().mul( radius );
  13001. const dy0 = texelSize.y.negate().mul( radius );
  13002. const dx1 = texelSize.x.mul( radius );
  13003. const dy1 = texelSize.y.mul( radius );
  13004. const dx2 = dx0.div( 2 );
  13005. const dy2 = dy0.div( 2 );
  13006. const dx3 = dx1.div( 2 );
  13007. const dy3 = dy1.div( 2 );
  13008. return add(
  13009. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  13010. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  13011. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  13012. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  13013. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  13014. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  13015. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  13016. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  13017. depthCompare( shadowCoord.xy, shadowCoord.z ),
  13018. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  13019. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  13020. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  13021. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  13022. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  13023. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  13024. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  13025. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  13026. ).mul( 1 / 17 );
  13027. } );
  13028. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  13029. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  13030. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  13031. const texelSize = vec2( 1 ).div( mapSize );
  13032. const dx = texelSize.x;
  13033. const dy = texelSize.y;
  13034. const uv = shadowCoord.xy;
  13035. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  13036. uv.subAssign( f.mul( texelSize ) );
  13037. return add(
  13038. depthCompare( uv, shadowCoord.z ),
  13039. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  13040. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  13041. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  13042. mix(
  13043. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  13044. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  13045. f.x
  13046. ),
  13047. mix(
  13048. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  13049. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  13050. f.x
  13051. ),
  13052. mix(
  13053. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  13054. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  13055. f.y
  13056. ),
  13057. mix(
  13058. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  13059. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  13060. f.y
  13061. ),
  13062. mix(
  13063. mix(
  13064. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  13065. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  13066. f.x
  13067. ),
  13068. mix(
  13069. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  13070. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  13071. f.x
  13072. ),
  13073. f.y
  13074. )
  13075. ).mul( 1 / 9 );
  13076. } );
  13077. // VSM
  13078. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  13079. const occlusion = float( 1 ).toVar();
  13080. const distribution = texture( depthTexture ).uv( shadowCoord.xy ).rg;
  13081. const hardShadow = step( shadowCoord.z, distribution.x );
  13082. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  13083. const distance = shadowCoord.z.sub( distribution.x );
  13084. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  13085. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  13086. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  13087. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  13088. } );
  13089. return occlusion;
  13090. } );
  13091. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  13092. const mean = float( 0 ).toVar();
  13093. const squaredMean = float( 0 ).toVar();
  13094. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  13095. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  13096. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  13097. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  13098. const depth = shadowPass.uv( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x;
  13099. mean.addAssign( depth );
  13100. squaredMean.addAssign( depth.mul( depth ) );
  13101. } );
  13102. mean.divAssign( samples );
  13103. squaredMean.divAssign( samples );
  13104. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  13105. return vec2( mean, std_dev );
  13106. } );
  13107. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  13108. const mean = float( 0 ).toVar();
  13109. const squaredMean = float( 0 ).toVar();
  13110. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  13111. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  13112. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  13113. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  13114. const distribution = shadowPass.uv( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  13115. mean.addAssign( distribution.x );
  13116. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  13117. } );
  13118. mean.divAssign( samples );
  13119. squaredMean.divAssign( samples );
  13120. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  13121. return vec2( mean, std_dev );
  13122. } );
  13123. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  13124. //
  13125. const _quadMesh$1 = /*@__PURE__*/ new QuadMesh();
  13126. class ShadowNode extends Node {
  13127. static get type() {
  13128. return 'ShadowNode';
  13129. }
  13130. constructor( light, shadow = null ) {
  13131. super();
  13132. this.light = light;
  13133. this.shadow = shadow || light.shadow;
  13134. this.shadowMap = null;
  13135. this.vsmShadowMapVertical = null;
  13136. this.vsmShadowMapHorizontal = null;
  13137. this.vsmMaterialVertical = null;
  13138. this.vsmMaterialHorizontal = null;
  13139. this.updateBeforeType = NodeUpdateType.RENDER;
  13140. this._node = null;
  13141. this.isShadowNode = true;
  13142. }
  13143. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow } ) {
  13144. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  13145. .and( shadowCoord.x.lessThanEqual( 1 ) )
  13146. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  13147. .and( shadowCoord.y.lessThanEqual( 1 ) )
  13148. .and( shadowCoord.z.lessThanEqual( 1 ) );
  13149. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow } );
  13150. return frustumTest.select( shadowNode, float( 1 ) );
  13151. }
  13152. setupShadowCoord( builder, shadowPosition ) {
  13153. const { shadow } = this;
  13154. const { renderer } = builder;
  13155. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  13156. let shadowCoord = shadowPosition;
  13157. let coordZ;
  13158. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  13159. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  13160. coordZ = shadowCoord.z;
  13161. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  13162. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  13163. }
  13164. } else {
  13165. const w = shadowCoord.w;
  13166. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  13167. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  13168. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  13169. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  13170. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  13171. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  13172. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  13173. }
  13174. shadowCoord = vec3(
  13175. shadowCoord.x,
  13176. shadowCoord.y.oneMinus(), // follow webgpu standards
  13177. coordZ.add( bias )
  13178. );
  13179. return shadowCoord;
  13180. }
  13181. getShadowFilterFn( type ) {
  13182. return _shadowFilterLib[ type ];
  13183. }
  13184. setupShadow( builder ) {
  13185. const { renderer } = builder;
  13186. const { light, shadow } = this;
  13187. const shadowMapType = renderer.shadowMap.type;
  13188. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  13189. depthTexture.compareFunction = LessCompare;
  13190. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  13191. shadowMap.depthTexture = depthTexture;
  13192. shadow.camera.updateProjectionMatrix();
  13193. // VSM
  13194. if ( shadowMapType === VSMShadowMap ) {
  13195. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  13196. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  13197. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  13198. const shadowPassVertical = texture( depthTexture );
  13199. const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  13200. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  13201. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  13202. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  13203. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  13204. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() );
  13205. material.name = 'VSMVertical';
  13206. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  13207. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() );
  13208. material.name = 'VSMHorizontal';
  13209. }
  13210. //
  13211. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  13212. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  13213. const shadowPosition = lightShadowMatrix( light ).mul( shadowWorldPosition.add( transformedNormalWorld.mul( normalBias ) ) );
  13214. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  13215. //
  13216. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  13217. if ( filterFn === null ) {
  13218. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  13219. }
  13220. const shadowDepthTexture = ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  13221. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow } );
  13222. const shadowColor = texture( shadowMap.texture, shadowCoord );
  13223. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  13224. this.shadowMap = shadowMap;
  13225. this.shadow.map = shadowMap;
  13226. return shadowOutput;
  13227. }
  13228. setup( builder ) {
  13229. if ( builder.renderer.shadowMap.enabled === false ) return;
  13230. return Fn( ( { material } ) => {
  13231. shadowWorldPosition.assign( material.shadowPositionNode || positionWorld );
  13232. let node = this._node;
  13233. if ( node === null ) {
  13234. this._node = node = this.setupShadow( builder );
  13235. }
  13236. if ( builder.material.shadowNode ) { // @deprecated, r171
  13237. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  13238. }
  13239. if ( builder.material.receivedShadowNode ) {
  13240. node = builder.material.receivedShadowNode( node );
  13241. }
  13242. return node;
  13243. } )();
  13244. }
  13245. renderShadow( frame ) {
  13246. const { shadow, shadowMap } = this;
  13247. const { renderer, scene } = frame;
  13248. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height );
  13249. renderer.render( scene, shadow.camera );
  13250. }
  13251. updateShadow( frame ) {
  13252. const { shadowMap, light, shadow } = this;
  13253. const { renderer, scene, camera } = frame;
  13254. const shadowType = renderer.shadowMap.type;
  13255. const depthVersion = shadowMap.depthTexture.version;
  13256. this._depthVersionCached = depthVersion;
  13257. const currentOverrideMaterial = scene.overrideMaterial;
  13258. scene.overrideMaterial = getShadowMaterial( light );
  13259. shadow.camera.layers.mask = camera.layers.mask;
  13260. const currentRenderTarget = renderer.getRenderTarget();
  13261. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  13262. const currentMRT = renderer.getMRT();
  13263. renderer.setMRT( null );
  13264. renderer.setRenderObjectFunction( ( object, ...params ) => {
  13265. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  13266. renderer.renderObject( object, ...params );
  13267. }
  13268. } );
  13269. renderer.setRenderTarget( shadowMap );
  13270. this.renderShadow( frame );
  13271. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  13272. // vsm blur pass
  13273. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  13274. this.vsmPass( renderer );
  13275. }
  13276. renderer.setRenderTarget( currentRenderTarget );
  13277. renderer.setMRT( currentMRT );
  13278. scene.overrideMaterial = currentOverrideMaterial;
  13279. }
  13280. vsmPass( renderer ) {
  13281. const { shadow } = this;
  13282. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height );
  13283. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height );
  13284. renderer.setRenderTarget( this.vsmShadowMapVertical );
  13285. _quadMesh$1.material = this.vsmMaterialVertical;
  13286. _quadMesh$1.render( renderer );
  13287. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  13288. _quadMesh$1.material = this.vsmMaterialHorizontal;
  13289. _quadMesh$1.render( renderer );
  13290. }
  13291. dispose() {
  13292. this.shadowMap.dispose();
  13293. this.shadowMap = null;
  13294. if ( this.vsmShadowMapVertical !== null ) {
  13295. this.vsmShadowMapVertical.dispose();
  13296. this.vsmShadowMapVertical = null;
  13297. this.vsmMaterialVertical.dispose();
  13298. this.vsmMaterialVertical = null;
  13299. }
  13300. if ( this.vsmShadowMapHorizontal !== null ) {
  13301. this.vsmShadowMapHorizontal.dispose();
  13302. this.vsmShadowMapHorizontal = null;
  13303. this.vsmMaterialHorizontal.dispose();
  13304. this.vsmMaterialHorizontal = null;
  13305. }
  13306. this.updateBeforeType = NodeUpdateType.NONE;
  13307. }
  13308. updateBefore( frame ) {
  13309. const { shadow } = this;
  13310. const needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  13311. if ( needsUpdate ) {
  13312. this.updateShadow( frame );
  13313. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  13314. shadow.needsUpdate = false;
  13315. }
  13316. }
  13317. }
  13318. }
  13319. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  13320. class AnalyticLightNode extends LightingNode {
  13321. static get type() {
  13322. return 'AnalyticLightNode';
  13323. }
  13324. constructor( light = null ) {
  13325. super();
  13326. this.light = light;
  13327. this.color = new Color();
  13328. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  13329. this.baseColorNode = null;
  13330. this.shadowNode = null;
  13331. this.shadowColorNode = null;
  13332. this.isAnalyticLightNode = true;
  13333. this.updateType = NodeUpdateType.FRAME;
  13334. }
  13335. getCacheKey() {
  13336. return hash$1( super.getCacheKey(), this.light.id, this.light.castShadow ? 1 : 0 );
  13337. }
  13338. getHash() {
  13339. return this.light.uuid;
  13340. }
  13341. setupShadowNode() {
  13342. return shadow( this.light );
  13343. }
  13344. setupShadow( builder ) {
  13345. const { renderer } = builder;
  13346. if ( renderer.shadowMap.enabled === false ) return;
  13347. let shadowColorNode = this.shadowColorNode;
  13348. if ( shadowColorNode === null ) {
  13349. const customShadowNode = this.light.shadow.shadowNode;
  13350. let shadowNode;
  13351. if ( customShadowNode !== undefined ) {
  13352. shadowNode = nodeObject( customShadowNode );
  13353. } else {
  13354. shadowNode = this.setupShadowNode( builder );
  13355. }
  13356. this.shadowNode = shadowNode;
  13357. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  13358. this.baseColorNode = this.colorNode;
  13359. }
  13360. //
  13361. this.colorNode = shadowColorNode;
  13362. }
  13363. setup( builder ) {
  13364. this.colorNode = this.baseColorNode || this.colorNode;
  13365. if ( this.light.castShadow ) {
  13366. if ( builder.object.receiveShadow ) {
  13367. this.setupShadow( builder );
  13368. }
  13369. } else if ( this.shadowNode !== null ) {
  13370. this.shadowNode.dispose();
  13371. this.shadowNode = null;
  13372. this.shadowColorNode = null;
  13373. }
  13374. }
  13375. update( /*frame*/ ) {
  13376. const { light } = this;
  13377. this.color.copy( light.color ).multiplyScalar( light.intensity );
  13378. }
  13379. }
  13380. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => {
  13381. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  13382. // based upon Frostbite 3 Moving to Physically-based Rendering
  13383. // page 32, equation 26: E[window1]
  13384. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  13385. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  13386. return cutoffDistance.greaterThan( 0 ).select(
  13387. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  13388. distanceFalloff
  13389. );
  13390. } ); // validated
  13391. const _clearColor$2 = /*@__PURE__*/ new Color();
  13392. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  13393. // vector suitable for 2D texture mapping. This code uses the following layout for the
  13394. // 2D texture:
  13395. //
  13396. // xzXZ
  13397. // y Y
  13398. //
  13399. // Y - Positive y direction
  13400. // y - Negative y direction
  13401. // X - Positive x direction
  13402. // x - Negative x direction
  13403. // Z - Positive z direction
  13404. // z - Negative z direction
  13405. //
  13406. // Source and test bed:
  13407. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  13408. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  13409. const v = pos.toVar();
  13410. // Number of texels to avoid at the edge of each square
  13411. const absV = abs( v );
  13412. // Intersect unit cube
  13413. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  13414. absV.mulAssign( scaleToCube );
  13415. // Apply scale to avoid seams
  13416. // two texels less per square (one texel will do for NEAREST)
  13417. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  13418. // Unwrap
  13419. // space: -1 ... 1 range for each square
  13420. //
  13421. // #X## dim := ( 4 , 2 )
  13422. // # # center := ( 1 , 1 )
  13423. const planar = vec2( v.xy ).toVar();
  13424. const almostATexel = texelSizeY.mul( 1.5 );
  13425. const almostOne = almostATexel.oneMinus();
  13426. If( absV.z.greaterThanEqual( almostOne ), () => {
  13427. If( v.z.greaterThan( 0.0 ), () => {
  13428. planar.x.assign( sub( 4.0, v.x ) );
  13429. } );
  13430. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  13431. const signX = sign( v.x );
  13432. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  13433. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  13434. const signY = sign( v.y );
  13435. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  13436. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  13437. } );
  13438. // Transform to UV space
  13439. // scale := 0.5 / dim
  13440. // translate := ( center + 0.5 ) / dim
  13441. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  13442. } ).setLayout( {
  13443. name: 'cubeToUV',
  13444. type: 'vec2',
  13445. inputs: [
  13446. { name: 'pos', type: 'vec3' },
  13447. { name: 'texelSizeY', type: 'float' }
  13448. ]
  13449. } );
  13450. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  13451. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  13452. } );
  13453. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  13454. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  13455. const offset = vec2( - 1.0, 1.0 ).mul( radius ).mul( texelSize.y );
  13456. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  13457. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  13458. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  13459. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  13460. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  13461. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  13462. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  13463. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  13464. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  13465. .mul( 1.0 / 9.0 );
  13466. } );
  13467. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  13468. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  13469. // the vector from the light to the world-space position of the fragment.
  13470. const lightToPosition = shadowCoord.xyz.toVar();
  13471. const lightToPositionLength = lightToPosition.length();
  13472. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  13473. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  13474. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  13475. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  13476. const result = float( 1.0 ).toVar();
  13477. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  13478. // dp = normalized distance from light to fragment position
  13479. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  13480. dp.addAssign( bias );
  13481. // bd3D = base direction 3D
  13482. const bd3D = lightToPosition.normalize();
  13483. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  13484. // percentage-closer filtering
  13485. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  13486. } );
  13487. return result;
  13488. } );
  13489. const _viewport = /*@__PURE__*/ new Vector4();
  13490. const _viewportSize = /*@__PURE__*/ new Vector2();
  13491. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  13492. //
  13493. class PointShadowNode extends ShadowNode {
  13494. static get type() {
  13495. return 'PointShadowNode';
  13496. }
  13497. constructor( light, shadow = null ) {
  13498. super( light, shadow );
  13499. }
  13500. getShadowFilterFn( type ) {
  13501. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  13502. }
  13503. setupShadowCoord( builder, shadowPosition ) {
  13504. return shadowPosition;
  13505. }
  13506. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  13507. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  13508. }
  13509. renderShadow( frame ) {
  13510. const { shadow, shadowMap, light } = this;
  13511. const { renderer, scene } = frame;
  13512. const shadowFrameExtents = shadow.getFrameExtents();
  13513. _shadowMapSize.copy( shadow.mapSize );
  13514. _shadowMapSize.multiply( shadowFrameExtents );
  13515. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  13516. _viewportSize.copy( shadow.mapSize );
  13517. //
  13518. const previousAutoClear = renderer.autoClear;
  13519. const previousClearColor = renderer.getClearColor( _clearColor$2 );
  13520. const previousClearAlpha = renderer.getClearAlpha();
  13521. renderer.autoClear = false;
  13522. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  13523. renderer.clear();
  13524. const viewportCount = shadow.getViewportCount();
  13525. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  13526. const viewport = shadow.getViewport( vp );
  13527. const x = _viewportSize.x * viewport.x;
  13528. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  13529. _viewport.set(
  13530. x,
  13531. y,
  13532. _viewportSize.x * viewport.z,
  13533. _viewportSize.y * viewport.w
  13534. );
  13535. shadowMap.viewport.copy( _viewport );
  13536. shadow.updateMatrices( light, vp );
  13537. renderer.render( scene, shadow.camera );
  13538. }
  13539. //
  13540. renderer.autoClear = previousAutoClear;
  13541. renderer.setClearColor( previousClearColor, previousClearAlpha );
  13542. }
  13543. }
  13544. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  13545. const directPointLight = Fn( ( { color, lightViewPosition, cutoffDistance, decayExponent }, builder ) => {
  13546. const lightingModel = builder.context.lightingModel;
  13547. const lVector = lightViewPosition.sub( positionView ); // @TODO: Add it into LightNode
  13548. const lightDirection = lVector.normalize();
  13549. const lightDistance = lVector.length();
  13550. const lightAttenuation = getDistanceAttenuation( {
  13551. lightDistance,
  13552. cutoffDistance,
  13553. decayExponent
  13554. } );
  13555. const lightColor = color.mul( lightAttenuation );
  13556. const reflectedLight = builder.context.reflectedLight;
  13557. lightingModel.direct( {
  13558. lightDirection,
  13559. lightColor,
  13560. reflectedLight
  13561. }, builder.stack, builder );
  13562. } );
  13563. class PointLightNode extends AnalyticLightNode {
  13564. static get type() {
  13565. return 'PointLightNode';
  13566. }
  13567. constructor( light = null ) {
  13568. super( light );
  13569. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  13570. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  13571. }
  13572. update( frame ) {
  13573. const { light } = this;
  13574. super.update( frame );
  13575. this.cutoffDistanceNode.value = light.distance;
  13576. this.decayExponentNode.value = light.decay;
  13577. }
  13578. setupShadowNode() {
  13579. return pointShadow( this.light );
  13580. }
  13581. setup( builder ) {
  13582. super.setup( builder );
  13583. directPointLight( {
  13584. color: this.colorNode,
  13585. lightViewPosition: lightViewPosition( this.light ),
  13586. cutoffDistance: this.cutoffDistanceNode,
  13587. decayExponent: this.decayExponentNode
  13588. } ).append();
  13589. }
  13590. }
  13591. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  13592. const uv = coord.mul( 2.0 );
  13593. const cx = uv.x.floor();
  13594. const cy = uv.y.floor();
  13595. const result = cx.add( cy ).mod( 2.0 );
  13596. return result.sign();
  13597. } );
  13598. // Three.js Transpiler
  13599. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  13600. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  13601. const f = float( f_immutable ).toVar();
  13602. const t = float( t_immutable ).toVar();
  13603. const b = bool( b_immutable ).toVar();
  13604. return select( b, t, f );
  13605. } ).setLayout( {
  13606. name: 'mx_select',
  13607. type: 'float',
  13608. inputs: [
  13609. { name: 'b', type: 'bool' },
  13610. { name: 't', type: 'float' },
  13611. { name: 'f', type: 'float' }
  13612. ]
  13613. } );
  13614. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  13615. const b = bool( b_immutable ).toVar();
  13616. const val = float( val_immutable ).toVar();
  13617. return select( b, val.negate(), val );
  13618. } ).setLayout( {
  13619. name: 'mx_negate_if',
  13620. type: 'float',
  13621. inputs: [
  13622. { name: 'val', type: 'float' },
  13623. { name: 'b', type: 'bool' }
  13624. ]
  13625. } );
  13626. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  13627. const x = float( x_immutable ).toVar();
  13628. return int( floor( x ) );
  13629. } ).setLayout( {
  13630. name: 'mx_floor',
  13631. type: 'int',
  13632. inputs: [
  13633. { name: 'x', type: 'float' }
  13634. ]
  13635. } );
  13636. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  13637. const x = float( x_immutable ).toVar();
  13638. i.assign( mx_floor( x ) );
  13639. return x.sub( float( i ) );
  13640. } );
  13641. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  13642. const t = float( t_immutable ).toVar();
  13643. const s = float( s_immutable ).toVar();
  13644. const v3 = float( v3_immutable ).toVar();
  13645. const v2 = float( v2_immutable ).toVar();
  13646. const v1 = float( v1_immutable ).toVar();
  13647. const v0 = float( v0_immutable ).toVar();
  13648. const s1 = float( sub( 1.0, s ) ).toVar();
  13649. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  13650. } ).setLayout( {
  13651. name: 'mx_bilerp_0',
  13652. type: 'float',
  13653. inputs: [
  13654. { name: 'v0', type: 'float' },
  13655. { name: 'v1', type: 'float' },
  13656. { name: 'v2', type: 'float' },
  13657. { name: 'v3', type: 'float' },
  13658. { name: 's', type: 'float' },
  13659. { name: 't', type: 'float' }
  13660. ]
  13661. } );
  13662. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  13663. const t = float( t_immutable ).toVar();
  13664. const s = float( s_immutable ).toVar();
  13665. const v3 = vec3( v3_immutable ).toVar();
  13666. const v2 = vec3( v2_immutable ).toVar();
  13667. const v1 = vec3( v1_immutable ).toVar();
  13668. const v0 = vec3( v0_immutable ).toVar();
  13669. const s1 = float( sub( 1.0, s ) ).toVar();
  13670. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  13671. } ).setLayout( {
  13672. name: 'mx_bilerp_1',
  13673. type: 'vec3',
  13674. inputs: [
  13675. { name: 'v0', type: 'vec3' },
  13676. { name: 'v1', type: 'vec3' },
  13677. { name: 'v2', type: 'vec3' },
  13678. { name: 'v3', type: 'vec3' },
  13679. { name: 's', type: 'float' },
  13680. { name: 't', type: 'float' }
  13681. ]
  13682. } );
  13683. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  13684. 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 ] ) => {
  13685. const r = float( r_immutable ).toVar();
  13686. const t = float( t_immutable ).toVar();
  13687. const s = float( s_immutable ).toVar();
  13688. const v7 = float( v7_immutable ).toVar();
  13689. const v6 = float( v6_immutable ).toVar();
  13690. const v5 = float( v5_immutable ).toVar();
  13691. const v4 = float( v4_immutable ).toVar();
  13692. const v3 = float( v3_immutable ).toVar();
  13693. const v2 = float( v2_immutable ).toVar();
  13694. const v1 = float( v1_immutable ).toVar();
  13695. const v0 = float( v0_immutable ).toVar();
  13696. const s1 = float( sub( 1.0, s ) ).toVar();
  13697. const t1 = float( sub( 1.0, t ) ).toVar();
  13698. const r1 = float( sub( 1.0, r ) ).toVar();
  13699. 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 ) ) ) ) ) );
  13700. } ).setLayout( {
  13701. name: 'mx_trilerp_0',
  13702. type: 'float',
  13703. inputs: [
  13704. { name: 'v0', type: 'float' },
  13705. { name: 'v1', type: 'float' },
  13706. { name: 'v2', type: 'float' },
  13707. { name: 'v3', type: 'float' },
  13708. { name: 'v4', type: 'float' },
  13709. { name: 'v5', type: 'float' },
  13710. { name: 'v6', type: 'float' },
  13711. { name: 'v7', type: 'float' },
  13712. { name: 's', type: 'float' },
  13713. { name: 't', type: 'float' },
  13714. { name: 'r', type: 'float' }
  13715. ]
  13716. } );
  13717. 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 ] ) => {
  13718. const r = float( r_immutable ).toVar();
  13719. const t = float( t_immutable ).toVar();
  13720. const s = float( s_immutable ).toVar();
  13721. const v7 = vec3( v7_immutable ).toVar();
  13722. const v6 = vec3( v6_immutable ).toVar();
  13723. const v5 = vec3( v5_immutable ).toVar();
  13724. const v4 = vec3( v4_immutable ).toVar();
  13725. const v3 = vec3( v3_immutable ).toVar();
  13726. const v2 = vec3( v2_immutable ).toVar();
  13727. const v1 = vec3( v1_immutable ).toVar();
  13728. const v0 = vec3( v0_immutable ).toVar();
  13729. const s1 = float( sub( 1.0, s ) ).toVar();
  13730. const t1 = float( sub( 1.0, t ) ).toVar();
  13731. const r1 = float( sub( 1.0, r ) ).toVar();
  13732. 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 ) ) ) ) ) );
  13733. } ).setLayout( {
  13734. name: 'mx_trilerp_1',
  13735. type: 'vec3',
  13736. inputs: [
  13737. { name: 'v0', type: 'vec3' },
  13738. { name: 'v1', type: 'vec3' },
  13739. { name: 'v2', type: 'vec3' },
  13740. { name: 'v3', type: 'vec3' },
  13741. { name: 'v4', type: 'vec3' },
  13742. { name: 'v5', type: 'vec3' },
  13743. { name: 'v6', type: 'vec3' },
  13744. { name: 'v7', type: 'vec3' },
  13745. { name: 's', type: 'float' },
  13746. { name: 't', type: 'float' },
  13747. { name: 'r', type: 'float' }
  13748. ]
  13749. } );
  13750. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  13751. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  13752. const y = float( y_immutable ).toVar();
  13753. const x = float( x_immutable ).toVar();
  13754. const hash = uint( hash_immutable ).toVar();
  13755. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  13756. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  13757. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  13758. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  13759. } ).setLayout( {
  13760. name: 'mx_gradient_float_0',
  13761. type: 'float',
  13762. inputs: [
  13763. { name: 'hash', type: 'uint' },
  13764. { name: 'x', type: 'float' },
  13765. { name: 'y', type: 'float' }
  13766. ]
  13767. } );
  13768. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  13769. const z = float( z_immutable ).toVar();
  13770. const y = float( y_immutable ).toVar();
  13771. const x = float( x_immutable ).toVar();
  13772. const hash = uint( hash_immutable ).toVar();
  13773. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  13774. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  13775. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  13776. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  13777. } ).setLayout( {
  13778. name: 'mx_gradient_float_1',
  13779. type: 'float',
  13780. inputs: [
  13781. { name: 'hash', type: 'uint' },
  13782. { name: 'x', type: 'float' },
  13783. { name: 'y', type: 'float' },
  13784. { name: 'z', type: 'float' }
  13785. ]
  13786. } );
  13787. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  13788. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  13789. const y = float( y_immutable ).toVar();
  13790. const x = float( x_immutable ).toVar();
  13791. const hash = uvec3( hash_immutable ).toVar();
  13792. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  13793. } ).setLayout( {
  13794. name: 'mx_gradient_vec3_0',
  13795. type: 'vec3',
  13796. inputs: [
  13797. { name: 'hash', type: 'uvec3' },
  13798. { name: 'x', type: 'float' },
  13799. { name: 'y', type: 'float' }
  13800. ]
  13801. } );
  13802. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  13803. const z = float( z_immutable ).toVar();
  13804. const y = float( y_immutable ).toVar();
  13805. const x = float( x_immutable ).toVar();
  13806. const hash = uvec3( hash_immutable ).toVar();
  13807. 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 ) );
  13808. } ).setLayout( {
  13809. name: 'mx_gradient_vec3_1',
  13810. type: 'vec3',
  13811. inputs: [
  13812. { name: 'hash', type: 'uvec3' },
  13813. { name: 'x', type: 'float' },
  13814. { name: 'y', type: 'float' },
  13815. { name: 'z', type: 'float' }
  13816. ]
  13817. } );
  13818. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  13819. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  13820. const v = float( v_immutable ).toVar();
  13821. return mul( 0.6616, v );
  13822. } ).setLayout( {
  13823. name: 'mx_gradient_scale2d_0',
  13824. type: 'float',
  13825. inputs: [
  13826. { name: 'v', type: 'float' }
  13827. ]
  13828. } );
  13829. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  13830. const v = float( v_immutable ).toVar();
  13831. return mul( 0.9820, v );
  13832. } ).setLayout( {
  13833. name: 'mx_gradient_scale3d_0',
  13834. type: 'float',
  13835. inputs: [
  13836. { name: 'v', type: 'float' }
  13837. ]
  13838. } );
  13839. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  13840. const v = vec3( v_immutable ).toVar();
  13841. return mul( 0.6616, v );
  13842. } ).setLayout( {
  13843. name: 'mx_gradient_scale2d_1',
  13844. type: 'vec3',
  13845. inputs: [
  13846. { name: 'v', type: 'vec3' }
  13847. ]
  13848. } );
  13849. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  13850. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  13851. const v = vec3( v_immutable ).toVar();
  13852. return mul( 0.9820, v );
  13853. } ).setLayout( {
  13854. name: 'mx_gradient_scale3d_1',
  13855. type: 'vec3',
  13856. inputs: [
  13857. { name: 'v', type: 'vec3' }
  13858. ]
  13859. } );
  13860. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  13861. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  13862. const k = int( k_immutable ).toVar();
  13863. const x = uint( x_immutable ).toVar();
  13864. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  13865. } ).setLayout( {
  13866. name: 'mx_rotl32',
  13867. type: 'uint',
  13868. inputs: [
  13869. { name: 'x', type: 'uint' },
  13870. { name: 'k', type: 'int' }
  13871. ]
  13872. } );
  13873. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  13874. a.subAssign( c );
  13875. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  13876. c.addAssign( b );
  13877. b.subAssign( a );
  13878. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  13879. a.addAssign( c );
  13880. c.subAssign( b );
  13881. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  13882. b.addAssign( a );
  13883. a.subAssign( c );
  13884. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  13885. c.addAssign( b );
  13886. b.subAssign( a );
  13887. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  13888. a.addAssign( c );
  13889. c.subAssign( b );
  13890. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  13891. b.addAssign( a );
  13892. } );
  13893. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  13894. const c = uint( c_immutable ).toVar();
  13895. const b = uint( b_immutable ).toVar();
  13896. const a = uint( a_immutable ).toVar();
  13897. c.bitXorAssign( b );
  13898. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  13899. a.bitXorAssign( c );
  13900. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  13901. b.bitXorAssign( a );
  13902. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  13903. c.bitXorAssign( b );
  13904. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  13905. a.bitXorAssign( c );
  13906. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  13907. b.bitXorAssign( a );
  13908. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  13909. c.bitXorAssign( b );
  13910. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  13911. return c;
  13912. } ).setLayout( {
  13913. name: 'mx_bjfinal',
  13914. type: 'uint',
  13915. inputs: [
  13916. { name: 'a', type: 'uint' },
  13917. { name: 'b', type: 'uint' },
  13918. { name: 'c', type: 'uint' }
  13919. ]
  13920. } );
  13921. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  13922. const bits = uint( bits_immutable ).toVar();
  13923. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  13924. } ).setLayout( {
  13925. name: 'mx_bits_to_01',
  13926. type: 'float',
  13927. inputs: [
  13928. { name: 'bits', type: 'uint' }
  13929. ]
  13930. } );
  13931. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  13932. const t = float( t_immutable ).toVar();
  13933. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  13934. } ).setLayout( {
  13935. name: 'mx_fade',
  13936. type: 'float',
  13937. inputs: [
  13938. { name: 't', type: 'float' }
  13939. ]
  13940. } );
  13941. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  13942. const x = int( x_immutable ).toVar();
  13943. const len = uint( uint( 1 ) ).toVar();
  13944. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  13945. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  13946. } ).setLayout( {
  13947. name: 'mx_hash_int_0',
  13948. type: 'uint',
  13949. inputs: [
  13950. { name: 'x', type: 'int' }
  13951. ]
  13952. } );
  13953. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  13954. const y = int( y_immutable ).toVar();
  13955. const x = int( x_immutable ).toVar();
  13956. const len = uint( uint( 2 ) ).toVar();
  13957. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  13958. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  13959. a.addAssign( uint( x ) );
  13960. b.addAssign( uint( y ) );
  13961. return mx_bjfinal( a, b, c );
  13962. } ).setLayout( {
  13963. name: 'mx_hash_int_1',
  13964. type: 'uint',
  13965. inputs: [
  13966. { name: 'x', type: 'int' },
  13967. { name: 'y', type: 'int' }
  13968. ]
  13969. } );
  13970. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  13971. const z = int( z_immutable ).toVar();
  13972. const y = int( y_immutable ).toVar();
  13973. const x = int( x_immutable ).toVar();
  13974. const len = uint( uint( 3 ) ).toVar();
  13975. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  13976. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  13977. a.addAssign( uint( x ) );
  13978. b.addAssign( uint( y ) );
  13979. c.addAssign( uint( z ) );
  13980. return mx_bjfinal( a, b, c );
  13981. } ).setLayout( {
  13982. name: 'mx_hash_int_2',
  13983. type: 'uint',
  13984. inputs: [
  13985. { name: 'x', type: 'int' },
  13986. { name: 'y', type: 'int' },
  13987. { name: 'z', type: 'int' }
  13988. ]
  13989. } );
  13990. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  13991. const xx = int( xx_immutable ).toVar();
  13992. const z = int( z_immutable ).toVar();
  13993. const y = int( y_immutable ).toVar();
  13994. const x = int( x_immutable ).toVar();
  13995. const len = uint( uint( 4 ) ).toVar();
  13996. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  13997. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  13998. a.addAssign( uint( x ) );
  13999. b.addAssign( uint( y ) );
  14000. c.addAssign( uint( z ) );
  14001. mx_bjmix( a, b, c );
  14002. a.addAssign( uint( xx ) );
  14003. return mx_bjfinal( a, b, c );
  14004. } ).setLayout( {
  14005. name: 'mx_hash_int_3',
  14006. type: 'uint',
  14007. inputs: [
  14008. { name: 'x', type: 'int' },
  14009. { name: 'y', type: 'int' },
  14010. { name: 'z', type: 'int' },
  14011. { name: 'xx', type: 'int' }
  14012. ]
  14013. } );
  14014. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  14015. const yy = int( yy_immutable ).toVar();
  14016. const xx = int( xx_immutable ).toVar();
  14017. const z = int( z_immutable ).toVar();
  14018. const y = int( y_immutable ).toVar();
  14019. const x = int( x_immutable ).toVar();
  14020. const len = uint( uint( 5 ) ).toVar();
  14021. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  14022. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  14023. a.addAssign( uint( x ) );
  14024. b.addAssign( uint( y ) );
  14025. c.addAssign( uint( z ) );
  14026. mx_bjmix( a, b, c );
  14027. a.addAssign( uint( xx ) );
  14028. b.addAssign( uint( yy ) );
  14029. return mx_bjfinal( a, b, c );
  14030. } ).setLayout( {
  14031. name: 'mx_hash_int_4',
  14032. type: 'uint',
  14033. inputs: [
  14034. { name: 'x', type: 'int' },
  14035. { name: 'y', type: 'int' },
  14036. { name: 'z', type: 'int' },
  14037. { name: 'xx', type: 'int' },
  14038. { name: 'yy', type: 'int' }
  14039. ]
  14040. } );
  14041. 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 ] );
  14042. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  14043. const y = int( y_immutable ).toVar();
  14044. const x = int( x_immutable ).toVar();
  14045. const h = uint( mx_hash_int( x, y ) ).toVar();
  14046. const result = uvec3().toVar();
  14047. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  14048. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  14049. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  14050. return result;
  14051. } ).setLayout( {
  14052. name: 'mx_hash_vec3_0',
  14053. type: 'uvec3',
  14054. inputs: [
  14055. { name: 'x', type: 'int' },
  14056. { name: 'y', type: 'int' }
  14057. ]
  14058. } );
  14059. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  14060. const z = int( z_immutable ).toVar();
  14061. const y = int( y_immutable ).toVar();
  14062. const x = int( x_immutable ).toVar();
  14063. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  14064. const result = uvec3().toVar();
  14065. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  14066. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  14067. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  14068. return result;
  14069. } ).setLayout( {
  14070. name: 'mx_hash_vec3_1',
  14071. type: 'uvec3',
  14072. inputs: [
  14073. { name: 'x', type: 'int' },
  14074. { name: 'y', type: 'int' },
  14075. { name: 'z', type: 'int' }
  14076. ]
  14077. } );
  14078. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  14079. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  14080. const p = vec2( p_immutable ).toVar();
  14081. const X = int().toVar(), Y = int().toVar();
  14082. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  14083. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  14084. const u = float( mx_fade( fx ) ).toVar();
  14085. const v = float( mx_fade( fy ) ).toVar();
  14086. 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();
  14087. return mx_gradient_scale2d( result );
  14088. } ).setLayout( {
  14089. name: 'mx_perlin_noise_float_0',
  14090. type: 'float',
  14091. inputs: [
  14092. { name: 'p', type: 'vec2' }
  14093. ]
  14094. } );
  14095. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  14096. const p = vec3( p_immutable ).toVar();
  14097. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  14098. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  14099. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  14100. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  14101. const u = float( mx_fade( fx ) ).toVar();
  14102. const v = float( mx_fade( fy ) ).toVar();
  14103. const w = float( mx_fade( fz ) ).toVar();
  14104. 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();
  14105. return mx_gradient_scale3d( result );
  14106. } ).setLayout( {
  14107. name: 'mx_perlin_noise_float_1',
  14108. type: 'float',
  14109. inputs: [
  14110. { name: 'p', type: 'vec3' }
  14111. ]
  14112. } );
  14113. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  14114. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  14115. const p = vec2( p_immutable ).toVar();
  14116. const X = int().toVar(), Y = int().toVar();
  14117. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  14118. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  14119. const u = float( mx_fade( fx ) ).toVar();
  14120. const v = float( mx_fade( fy ) ).toVar();
  14121. 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();
  14122. return mx_gradient_scale2d( result );
  14123. } ).setLayout( {
  14124. name: 'mx_perlin_noise_vec3_0',
  14125. type: 'vec3',
  14126. inputs: [
  14127. { name: 'p', type: 'vec2' }
  14128. ]
  14129. } );
  14130. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  14131. const p = vec3( p_immutable ).toVar();
  14132. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  14133. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  14134. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  14135. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  14136. const u = float( mx_fade( fx ) ).toVar();
  14137. const v = float( mx_fade( fy ) ).toVar();
  14138. const w = float( mx_fade( fz ) ).toVar();
  14139. 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();
  14140. return mx_gradient_scale3d( result );
  14141. } ).setLayout( {
  14142. name: 'mx_perlin_noise_vec3_1',
  14143. type: 'vec3',
  14144. inputs: [
  14145. { name: 'p', type: 'vec3' }
  14146. ]
  14147. } );
  14148. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  14149. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  14150. const p = float( p_immutable ).toVar();
  14151. const ix = int( mx_floor( p ) ).toVar();
  14152. return mx_bits_to_01( mx_hash_int( ix ) );
  14153. } ).setLayout( {
  14154. name: 'mx_cell_noise_float_0',
  14155. type: 'float',
  14156. inputs: [
  14157. { name: 'p', type: 'float' }
  14158. ]
  14159. } );
  14160. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  14161. const p = vec2( p_immutable ).toVar();
  14162. const ix = int( mx_floor( p.x ) ).toVar();
  14163. const iy = int( mx_floor( p.y ) ).toVar();
  14164. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  14165. } ).setLayout( {
  14166. name: 'mx_cell_noise_float_1',
  14167. type: 'float',
  14168. inputs: [
  14169. { name: 'p', type: 'vec2' }
  14170. ]
  14171. } );
  14172. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  14173. const p = vec3( p_immutable ).toVar();
  14174. const ix = int( mx_floor( p.x ) ).toVar();
  14175. const iy = int( mx_floor( p.y ) ).toVar();
  14176. const iz = int( mx_floor( p.z ) ).toVar();
  14177. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  14178. } ).setLayout( {
  14179. name: 'mx_cell_noise_float_2',
  14180. type: 'float',
  14181. inputs: [
  14182. { name: 'p', type: 'vec3' }
  14183. ]
  14184. } );
  14185. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  14186. const p = vec4( p_immutable ).toVar();
  14187. const ix = int( mx_floor( p.x ) ).toVar();
  14188. const iy = int( mx_floor( p.y ) ).toVar();
  14189. const iz = int( mx_floor( p.z ) ).toVar();
  14190. const iw = int( mx_floor( p.w ) ).toVar();
  14191. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  14192. } ).setLayout( {
  14193. name: 'mx_cell_noise_float_3',
  14194. type: 'float',
  14195. inputs: [
  14196. { name: 'p', type: 'vec4' }
  14197. ]
  14198. } );
  14199. 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 ] );
  14200. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  14201. const p = float( p_immutable ).toVar();
  14202. const ix = int( mx_floor( p ) ).toVar();
  14203. 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 ) ) ) );
  14204. } ).setLayout( {
  14205. name: 'mx_cell_noise_vec3_0',
  14206. type: 'vec3',
  14207. inputs: [
  14208. { name: 'p', type: 'float' }
  14209. ]
  14210. } );
  14211. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  14212. const p = vec2( p_immutable ).toVar();
  14213. const ix = int( mx_floor( p.x ) ).toVar();
  14214. const iy = int( mx_floor( p.y ) ).toVar();
  14215. 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 ) ) ) );
  14216. } ).setLayout( {
  14217. name: 'mx_cell_noise_vec3_1',
  14218. type: 'vec3',
  14219. inputs: [
  14220. { name: 'p', type: 'vec2' }
  14221. ]
  14222. } );
  14223. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  14224. const p = vec3( p_immutable ).toVar();
  14225. const ix = int( mx_floor( p.x ) ).toVar();
  14226. const iy = int( mx_floor( p.y ) ).toVar();
  14227. const iz = int( mx_floor( p.z ) ).toVar();
  14228. 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 ) ) ) );
  14229. } ).setLayout( {
  14230. name: 'mx_cell_noise_vec3_2',
  14231. type: 'vec3',
  14232. inputs: [
  14233. { name: 'p', type: 'vec3' }
  14234. ]
  14235. } );
  14236. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  14237. const p = vec4( p_immutable ).toVar();
  14238. const ix = int( mx_floor( p.x ) ).toVar();
  14239. const iy = int( mx_floor( p.y ) ).toVar();
  14240. const iz = int( mx_floor( p.z ) ).toVar();
  14241. const iw = int( mx_floor( p.w ) ).toVar();
  14242. 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 ) ) ) );
  14243. } ).setLayout( {
  14244. name: 'mx_cell_noise_vec3_3',
  14245. type: 'vec3',
  14246. inputs: [
  14247. { name: 'p', type: 'vec4' }
  14248. ]
  14249. } );
  14250. 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 ] );
  14251. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  14252. const diminish = float( diminish_immutable ).toVar();
  14253. const lacunarity = float( lacunarity_immutable ).toVar();
  14254. const octaves = int( octaves_immutable ).toVar();
  14255. const p = vec3( p_immutable ).toVar();
  14256. const result = float( 0.0 ).toVar();
  14257. const amplitude = float( 1.0 ).toVar();
  14258. Loop( octaves, () => {
  14259. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  14260. amplitude.mulAssign( diminish );
  14261. p.mulAssign( lacunarity );
  14262. } );
  14263. return result;
  14264. } ).setLayout( {
  14265. name: 'mx_fractal_noise_float',
  14266. type: 'float',
  14267. inputs: [
  14268. { name: 'p', type: 'vec3' },
  14269. { name: 'octaves', type: 'int' },
  14270. { name: 'lacunarity', type: 'float' },
  14271. { name: 'diminish', type: 'float' }
  14272. ]
  14273. } );
  14274. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  14275. const diminish = float( diminish_immutable ).toVar();
  14276. const lacunarity = float( lacunarity_immutable ).toVar();
  14277. const octaves = int( octaves_immutable ).toVar();
  14278. const p = vec3( p_immutable ).toVar();
  14279. const result = vec3( 0.0 ).toVar();
  14280. const amplitude = float( 1.0 ).toVar();
  14281. Loop( octaves, () => {
  14282. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  14283. amplitude.mulAssign( diminish );
  14284. p.mulAssign( lacunarity );
  14285. } );
  14286. return result;
  14287. } ).setLayout( {
  14288. name: 'mx_fractal_noise_vec3',
  14289. type: 'vec3',
  14290. inputs: [
  14291. { name: 'p', type: 'vec3' },
  14292. { name: 'octaves', type: 'int' },
  14293. { name: 'lacunarity', type: 'float' },
  14294. { name: 'diminish', type: 'float' }
  14295. ]
  14296. } );
  14297. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  14298. const diminish = float( diminish_immutable ).toVar();
  14299. const lacunarity = float( lacunarity_immutable ).toVar();
  14300. const octaves = int( octaves_immutable ).toVar();
  14301. const p = vec3( p_immutable ).toVar();
  14302. 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 ) );
  14303. } ).setLayout( {
  14304. name: 'mx_fractal_noise_vec2',
  14305. type: 'vec2',
  14306. inputs: [
  14307. { name: 'p', type: 'vec3' },
  14308. { name: 'octaves', type: 'int' },
  14309. { name: 'lacunarity', type: 'float' },
  14310. { name: 'diminish', type: 'float' }
  14311. ]
  14312. } );
  14313. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  14314. const diminish = float( diminish_immutable ).toVar();
  14315. const lacunarity = float( lacunarity_immutable ).toVar();
  14316. const octaves = int( octaves_immutable ).toVar();
  14317. const p = vec3( p_immutable ).toVar();
  14318. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  14319. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  14320. return vec4( c, f );
  14321. } ).setLayout( {
  14322. name: 'mx_fractal_noise_vec4',
  14323. type: 'vec4',
  14324. inputs: [
  14325. { name: 'p', type: 'vec3' },
  14326. { name: 'octaves', type: 'int' },
  14327. { name: 'lacunarity', type: 'float' },
  14328. { name: 'diminish', type: 'float' }
  14329. ]
  14330. } );
  14331. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  14332. const metric = int( metric_immutable ).toVar();
  14333. const jitter = float( jitter_immutable ).toVar();
  14334. const yoff = int( yoff_immutable ).toVar();
  14335. const xoff = int( xoff_immutable ).toVar();
  14336. const y = int( y_immutable ).toVar();
  14337. const x = int( x_immutable ).toVar();
  14338. const p = vec2( p_immutable ).toVar();
  14339. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  14340. const off = vec2( tmp.x, tmp.y ).toVar();
  14341. off.subAssign( 0.5 );
  14342. off.mulAssign( jitter );
  14343. off.addAssign( 0.5 );
  14344. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  14345. const diff = vec2( cellpos.sub( p ) ).toVar();
  14346. If( metric.equal( int( 2 ) ), () => {
  14347. return abs( diff.x ).add( abs( diff.y ) );
  14348. } );
  14349. If( metric.equal( int( 3 ) ), () => {
  14350. return max$1( abs( diff.x ), abs( diff.y ) );
  14351. } );
  14352. return dot( diff, diff );
  14353. } ).setLayout( {
  14354. name: 'mx_worley_distance_0',
  14355. type: 'float',
  14356. inputs: [
  14357. { name: 'p', type: 'vec2' },
  14358. { name: 'x', type: 'int' },
  14359. { name: 'y', type: 'int' },
  14360. { name: 'xoff', type: 'int' },
  14361. { name: 'yoff', type: 'int' },
  14362. { name: 'jitter', type: 'float' },
  14363. { name: 'metric', type: 'int' }
  14364. ]
  14365. } );
  14366. 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 ] ) => {
  14367. const metric = int( metric_immutable ).toVar();
  14368. const jitter = float( jitter_immutable ).toVar();
  14369. const zoff = int( zoff_immutable ).toVar();
  14370. const yoff = int( yoff_immutable ).toVar();
  14371. const xoff = int( xoff_immutable ).toVar();
  14372. const z = int( z_immutable ).toVar();
  14373. const y = int( y_immutable ).toVar();
  14374. const x = int( x_immutable ).toVar();
  14375. const p = vec3( p_immutable ).toVar();
  14376. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  14377. off.subAssign( 0.5 );
  14378. off.mulAssign( jitter );
  14379. off.addAssign( 0.5 );
  14380. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  14381. const diff = vec3( cellpos.sub( p ) ).toVar();
  14382. If( metric.equal( int( 2 ) ), () => {
  14383. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  14384. } );
  14385. If( metric.equal( int( 3 ) ), () => {
  14386. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  14387. } );
  14388. return dot( diff, diff );
  14389. } ).setLayout( {
  14390. name: 'mx_worley_distance_1',
  14391. type: 'float',
  14392. inputs: [
  14393. { name: 'p', type: 'vec3' },
  14394. { name: 'x', type: 'int' },
  14395. { name: 'y', type: 'int' },
  14396. { name: 'z', type: 'int' },
  14397. { name: 'xoff', type: 'int' },
  14398. { name: 'yoff', type: 'int' },
  14399. { name: 'zoff', type: 'int' },
  14400. { name: 'jitter', type: 'float' },
  14401. { name: 'metric', type: 'int' }
  14402. ]
  14403. } );
  14404. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  14405. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  14406. const metric = int( metric_immutable ).toVar();
  14407. const jitter = float( jitter_immutable ).toVar();
  14408. const p = vec2( p_immutable ).toVar();
  14409. const X = int().toVar(), Y = int().toVar();
  14410. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  14411. const sqdist = float( 1e6 ).toVar();
  14412. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  14413. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  14414. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  14415. sqdist.assign( min$1( sqdist, dist ) );
  14416. } );
  14417. } );
  14418. If( metric.equal( int( 0 ) ), () => {
  14419. sqdist.assign( sqrt( sqdist ) );
  14420. } );
  14421. return sqdist;
  14422. } ).setLayout( {
  14423. name: 'mx_worley_noise_float_0',
  14424. type: 'float',
  14425. inputs: [
  14426. { name: 'p', type: 'vec2' },
  14427. { name: 'jitter', type: 'float' },
  14428. { name: 'metric', type: 'int' }
  14429. ]
  14430. } );
  14431. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  14432. const metric = int( metric_immutable ).toVar();
  14433. const jitter = float( jitter_immutable ).toVar();
  14434. const p = vec2( p_immutable ).toVar();
  14435. const X = int().toVar(), Y = int().toVar();
  14436. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  14437. const sqdist = vec2( 1e6, 1e6 ).toVar();
  14438. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  14439. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  14440. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  14441. If( dist.lessThan( sqdist.x ), () => {
  14442. sqdist.y.assign( sqdist.x );
  14443. sqdist.x.assign( dist );
  14444. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  14445. sqdist.y.assign( dist );
  14446. } );
  14447. } );
  14448. } );
  14449. If( metric.equal( int( 0 ) ), () => {
  14450. sqdist.assign( sqrt( sqdist ) );
  14451. } );
  14452. return sqdist;
  14453. } ).setLayout( {
  14454. name: 'mx_worley_noise_vec2_0',
  14455. type: 'vec2',
  14456. inputs: [
  14457. { name: 'p', type: 'vec2' },
  14458. { name: 'jitter', type: 'float' },
  14459. { name: 'metric', type: 'int' }
  14460. ]
  14461. } );
  14462. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  14463. const metric = int( metric_immutable ).toVar();
  14464. const jitter = float( jitter_immutable ).toVar();
  14465. const p = vec2( p_immutable ).toVar();
  14466. const X = int().toVar(), Y = int().toVar();
  14467. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  14468. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  14469. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  14470. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  14471. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  14472. If( dist.lessThan( sqdist.x ), () => {
  14473. sqdist.z.assign( sqdist.y );
  14474. sqdist.y.assign( sqdist.x );
  14475. sqdist.x.assign( dist );
  14476. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  14477. sqdist.z.assign( sqdist.y );
  14478. sqdist.y.assign( dist );
  14479. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  14480. sqdist.z.assign( dist );
  14481. } );
  14482. } );
  14483. } );
  14484. If( metric.equal( int( 0 ) ), () => {
  14485. sqdist.assign( sqrt( sqdist ) );
  14486. } );
  14487. return sqdist;
  14488. } ).setLayout( {
  14489. name: 'mx_worley_noise_vec3_0',
  14490. type: 'vec3',
  14491. inputs: [
  14492. { name: 'p', type: 'vec2' },
  14493. { name: 'jitter', type: 'float' },
  14494. { name: 'metric', type: 'int' }
  14495. ]
  14496. } );
  14497. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  14498. const metric = int( metric_immutable ).toVar();
  14499. const jitter = float( jitter_immutable ).toVar();
  14500. const p = vec3( p_immutable ).toVar();
  14501. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  14502. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  14503. const sqdist = float( 1e6 ).toVar();
  14504. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  14505. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  14506. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  14507. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  14508. sqdist.assign( min$1( sqdist, dist ) );
  14509. } );
  14510. } );
  14511. } );
  14512. If( metric.equal( int( 0 ) ), () => {
  14513. sqdist.assign( sqrt( sqdist ) );
  14514. } );
  14515. return sqdist;
  14516. } ).setLayout( {
  14517. name: 'mx_worley_noise_float_1',
  14518. type: 'float',
  14519. inputs: [
  14520. { name: 'p', type: 'vec3' },
  14521. { name: 'jitter', type: 'float' },
  14522. { name: 'metric', type: 'int' }
  14523. ]
  14524. } );
  14525. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  14526. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  14527. const metric = int( metric_immutable ).toVar();
  14528. const jitter = float( jitter_immutable ).toVar();
  14529. const p = vec3( p_immutable ).toVar();
  14530. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  14531. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  14532. const sqdist = vec2( 1e6, 1e6 ).toVar();
  14533. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  14534. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  14535. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  14536. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  14537. If( dist.lessThan( sqdist.x ), () => {
  14538. sqdist.y.assign( sqdist.x );
  14539. sqdist.x.assign( dist );
  14540. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  14541. sqdist.y.assign( dist );
  14542. } );
  14543. } );
  14544. } );
  14545. } );
  14546. If( metric.equal( int( 0 ) ), () => {
  14547. sqdist.assign( sqrt( sqdist ) );
  14548. } );
  14549. return sqdist;
  14550. } ).setLayout( {
  14551. name: 'mx_worley_noise_vec2_1',
  14552. type: 'vec2',
  14553. inputs: [
  14554. { name: 'p', type: 'vec3' },
  14555. { name: 'jitter', type: 'float' },
  14556. { name: 'metric', type: 'int' }
  14557. ]
  14558. } );
  14559. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  14560. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  14561. const metric = int( metric_immutable ).toVar();
  14562. const jitter = float( jitter_immutable ).toVar();
  14563. const p = vec3( p_immutable ).toVar();
  14564. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  14565. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  14566. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  14567. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  14568. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  14569. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  14570. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  14571. If( dist.lessThan( sqdist.x ), () => {
  14572. sqdist.z.assign( sqdist.y );
  14573. sqdist.y.assign( sqdist.x );
  14574. sqdist.x.assign( dist );
  14575. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  14576. sqdist.z.assign( sqdist.y );
  14577. sqdist.y.assign( dist );
  14578. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  14579. sqdist.z.assign( dist );
  14580. } );
  14581. } );
  14582. } );
  14583. } );
  14584. If( metric.equal( int( 0 ) ), () => {
  14585. sqdist.assign( sqrt( sqdist ) );
  14586. } );
  14587. return sqdist;
  14588. } ).setLayout( {
  14589. name: 'mx_worley_noise_vec3_1',
  14590. type: 'vec3',
  14591. inputs: [
  14592. { name: 'p', type: 'vec3' },
  14593. { name: 'jitter', type: 'float' },
  14594. { name: 'metric', type: 'int' }
  14595. ]
  14596. } );
  14597. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  14598. // Three.js Transpiler
  14599. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  14600. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  14601. const s = hsv.y;
  14602. const v = hsv.z;
  14603. const result = vec3().toVar();
  14604. If( s.lessThan( 0.0001 ), () => {
  14605. result.assign( vec3( v, v, v ) );
  14606. } ).Else( () => {
  14607. let h = hsv.x;
  14608. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  14609. const hi = int( trunc( h ) );
  14610. const f = h.sub( float( hi ) );
  14611. const p = v.mul( s.oneMinus() );
  14612. const q = v.mul( s.mul( f ).oneMinus() );
  14613. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  14614. If( hi.equal( int( 0 ) ), () => {
  14615. result.assign( vec3( v, t, p ) );
  14616. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  14617. result.assign( vec3( q, v, p ) );
  14618. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  14619. result.assign( vec3( p, v, t ) );
  14620. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  14621. result.assign( vec3( p, q, v ) );
  14622. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  14623. result.assign( vec3( t, p, v ) );
  14624. } ).Else( () => {
  14625. result.assign( vec3( v, p, q ) );
  14626. } );
  14627. } );
  14628. return result;
  14629. } ).setLayout( {
  14630. name: 'mx_hsvtorgb',
  14631. type: 'vec3',
  14632. inputs: [
  14633. { name: 'hsv', type: 'vec3' }
  14634. ]
  14635. } );
  14636. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  14637. const c = vec3( c_immutable ).toVar();
  14638. const r = float( c.x ).toVar();
  14639. const g = float( c.y ).toVar();
  14640. const b = float( c.z ).toVar();
  14641. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  14642. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  14643. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  14644. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  14645. v.assign( maxcomp );
  14646. If( maxcomp.greaterThan( 0.0 ), () => {
  14647. s.assign( delta.div( maxcomp ) );
  14648. } ).Else( () => {
  14649. s.assign( 0.0 );
  14650. } );
  14651. If( s.lessThanEqual( 0.0 ), () => {
  14652. h.assign( 0.0 );
  14653. } ).Else( () => {
  14654. If( r.greaterThanEqual( maxcomp ), () => {
  14655. h.assign( g.sub( b ).div( delta ) );
  14656. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  14657. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  14658. } ).Else( () => {
  14659. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  14660. } );
  14661. h.mulAssign( 1.0 / 6.0 );
  14662. If( h.lessThan( 0.0 ), () => {
  14663. h.addAssign( 1.0 );
  14664. } );
  14665. } );
  14666. return vec3( h, s, v );
  14667. } ).setLayout( {
  14668. name: 'mx_rgbtohsv',
  14669. type: 'vec3',
  14670. inputs: [
  14671. { name: 'c', type: 'vec3' }
  14672. ]
  14673. } );
  14674. // Three.js Transpiler
  14675. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  14676. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  14677. const color = vec3( color_immutable ).toVar();
  14678. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  14679. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  14680. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  14681. return mix( linSeg, powSeg, isAbove );
  14682. } ).setLayout( {
  14683. name: 'mx_srgb_texture_to_lin_rec709',
  14684. type: 'vec3',
  14685. inputs: [
  14686. { name: 'color', type: 'vec3' }
  14687. ]
  14688. } );
  14689. const mx_aastep = ( threshold, value ) => {
  14690. threshold = float( threshold );
  14691. value = float( value );
  14692. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  14693. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  14694. };
  14695. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  14696. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  14697. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  14698. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  14699. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  14700. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  14701. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  14702. const mx_safepower = ( in1, in2 = 1 ) => {
  14703. in1 = float( in1 );
  14704. return in1.abs().pow( in2 ).mul( in1.sign() );
  14705. };
  14706. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  14707. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  14708. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  14709. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  14710. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  14711. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  14712. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  14713. return noise_vec4.mul( amplitude ).add( pivot );
  14714. };
  14715. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  14716. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  14717. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  14718. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  14719. 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 );
  14720. 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 );
  14721. 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 );
  14722. 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 );
  14723. // https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html
  14724. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  14725. const nDir = normalize( normal ).toVar( 'nDir' );
  14726. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmax' );
  14727. const rbmin = sub( float( - 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmin' );
  14728. const rbminmax = vec3().toVar( 'rbminmax' );
  14729. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  14730. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  14731. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  14732. const correction = min$1( min$1( rbminmax.x, rbminmax.y ), rbminmax.z ).toVar( 'correction' );
  14733. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar( 'boxIntersection' );
  14734. return boxIntersection.sub( cubePos );
  14735. } );
  14736. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  14737. // normal is assumed to have unit length
  14738. const x = normal.x, y = normal.y, z = normal.z;
  14739. // band 0
  14740. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  14741. // band 1
  14742. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  14743. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  14744. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  14745. // band 2
  14746. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  14747. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  14748. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  14749. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  14750. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  14751. return result;
  14752. } );
  14753. // constants
  14754. var TSL = /*#__PURE__*/Object.freeze({
  14755. __proto__: null,
  14756. BRDF_GGX: BRDF_GGX,
  14757. BRDF_Lambert: BRDF_Lambert,
  14758. BasicShadowFilter: BasicShadowFilter,
  14759. Break: Break,
  14760. Continue: Continue,
  14761. DFGApprox: DFGApprox,
  14762. D_GGX: D_GGX,
  14763. Discard: Discard,
  14764. EPSILON: EPSILON,
  14765. F_Schlick: F_Schlick,
  14766. Fn: Fn,
  14767. INFINITY: INFINITY,
  14768. If: If,
  14769. Loop: Loop,
  14770. NodeAccess: NodeAccess,
  14771. NodeShaderStage: NodeShaderStage,
  14772. NodeType: NodeType,
  14773. NodeUpdateType: NodeUpdateType,
  14774. PCFShadowFilter: PCFShadowFilter,
  14775. PCFSoftShadowFilter: PCFSoftShadowFilter,
  14776. PI: PI,
  14777. PI2: PI2,
  14778. Return: Return,
  14779. Schlick_to_F0: Schlick_to_F0,
  14780. ScriptableNodeResources: ScriptableNodeResources,
  14781. ShaderNode: ShaderNode,
  14782. TBNViewMatrix: TBNViewMatrix,
  14783. VSMShadowFilter: VSMShadowFilter,
  14784. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  14785. abs: abs,
  14786. acesFilmicToneMapping: acesFilmicToneMapping,
  14787. acos: acos,
  14788. add: add,
  14789. addMethodChaining: addMethodChaining,
  14790. addNodeElement: addNodeElement,
  14791. agxToneMapping: agxToneMapping,
  14792. all: all,
  14793. alphaT: alphaT,
  14794. and: and,
  14795. anisotropy: anisotropy,
  14796. anisotropyB: anisotropyB,
  14797. anisotropyT: anisotropyT,
  14798. any: any,
  14799. append: append,
  14800. arrayBuffer: arrayBuffer,
  14801. asin: asin,
  14802. assign: assign,
  14803. atan: atan,
  14804. atan2: atan2,
  14805. atomicAdd: atomicAdd,
  14806. atomicAnd: atomicAnd,
  14807. atomicFunc: atomicFunc,
  14808. atomicMax: atomicMax,
  14809. atomicMin: atomicMin,
  14810. atomicOr: atomicOr,
  14811. atomicStore: atomicStore,
  14812. atomicSub: atomicSub,
  14813. atomicXor: atomicXor,
  14814. attenuationColor: attenuationColor,
  14815. attenuationDistance: attenuationDistance,
  14816. attribute: attribute,
  14817. attributeArray: attributeArray,
  14818. backgroundBlurriness: backgroundBlurriness,
  14819. backgroundIntensity: backgroundIntensity,
  14820. backgroundRotation: backgroundRotation,
  14821. batch: batch,
  14822. billboarding: billboarding,
  14823. bitAnd: bitAnd,
  14824. bitNot: bitNot,
  14825. bitOr: bitOr,
  14826. bitXor: bitXor,
  14827. bitangentGeometry: bitangentGeometry,
  14828. bitangentLocal: bitangentLocal,
  14829. bitangentView: bitangentView,
  14830. bitangentWorld: bitangentWorld,
  14831. bitcast: bitcast,
  14832. blendBurn: blendBurn,
  14833. blendColor: blendColor,
  14834. blendDodge: blendDodge,
  14835. blendOverlay: blendOverlay,
  14836. blendScreen: blendScreen,
  14837. blur: blur,
  14838. bool: bool,
  14839. buffer: buffer,
  14840. bufferAttribute: bufferAttribute,
  14841. bumpMap: bumpMap,
  14842. burn: burn,
  14843. bvec2: bvec2,
  14844. bvec3: bvec3,
  14845. bvec4: bvec4,
  14846. bypass: bypass,
  14847. cache: cache,
  14848. call: call,
  14849. cameraFar: cameraFar,
  14850. cameraNear: cameraNear,
  14851. cameraNormalMatrix: cameraNormalMatrix,
  14852. cameraPosition: cameraPosition,
  14853. cameraProjectionMatrix: cameraProjectionMatrix,
  14854. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  14855. cameraViewMatrix: cameraViewMatrix,
  14856. cameraWorldMatrix: cameraWorldMatrix,
  14857. cbrt: cbrt,
  14858. cdl: cdl,
  14859. ceil: ceil,
  14860. checker: checker,
  14861. cineonToneMapping: cineonToneMapping,
  14862. clamp: clamp,
  14863. clearcoat: clearcoat,
  14864. clearcoatRoughness: clearcoatRoughness,
  14865. code: code,
  14866. color: color,
  14867. colorSpaceToWorking: colorSpaceToWorking,
  14868. colorToDirection: colorToDirection,
  14869. compute: compute,
  14870. cond: cond,
  14871. context: context,
  14872. convert: convert,
  14873. convertColorSpace: convertColorSpace,
  14874. convertToTexture: convertToTexture,
  14875. cos: cos,
  14876. cross: cross,
  14877. cubeTexture: cubeTexture,
  14878. dFdx: dFdx,
  14879. dFdy: dFdy,
  14880. dashSize: dashSize,
  14881. defaultBuildStages: defaultBuildStages,
  14882. defaultShaderStages: defaultShaderStages,
  14883. defined: defined,
  14884. degrees: degrees,
  14885. deltaTime: deltaTime,
  14886. densityFog: densityFog,
  14887. depth: depth,
  14888. depthPass: depthPass,
  14889. difference: difference,
  14890. diffuseColor: diffuseColor,
  14891. directPointLight: directPointLight,
  14892. directionToColor: directionToColor,
  14893. dispersion: dispersion,
  14894. distance: distance,
  14895. div: div,
  14896. dodge: dodge,
  14897. dot: dot,
  14898. drawIndex: drawIndex,
  14899. dynamicBufferAttribute: dynamicBufferAttribute,
  14900. element: element,
  14901. emissive: emissive,
  14902. equal: equal,
  14903. equals: equals,
  14904. equirectUV: equirectUV,
  14905. exp: exp,
  14906. exp2: exp2,
  14907. expression: expression,
  14908. faceDirection: faceDirection,
  14909. faceForward: faceForward,
  14910. float: float,
  14911. floor: floor,
  14912. fog: fog,
  14913. fract: fract,
  14914. frameGroup: frameGroup,
  14915. frameId: frameId,
  14916. frontFacing: frontFacing,
  14917. fwidth: fwidth,
  14918. gain: gain,
  14919. gapSize: gapSize,
  14920. getConstNodeType: getConstNodeType,
  14921. getCurrentStack: getCurrentStack,
  14922. getDirection: getDirection,
  14923. getDistanceAttenuation: getDistanceAttenuation,
  14924. getGeometryRoughness: getGeometryRoughness,
  14925. getNormalFromDepth: getNormalFromDepth,
  14926. getParallaxCorrectNormal: getParallaxCorrectNormal,
  14927. getRoughness: getRoughness,
  14928. getScreenPosition: getScreenPosition,
  14929. getShIrradianceAt: getShIrradianceAt,
  14930. getTextureIndex: getTextureIndex,
  14931. getViewPosition: getViewPosition,
  14932. glsl: glsl,
  14933. glslFn: glslFn,
  14934. grayscale: grayscale,
  14935. greaterThan: greaterThan,
  14936. greaterThanEqual: greaterThanEqual,
  14937. hash: hash,
  14938. highPrecisionModelNormalViewMatrix: highPrecisionModelNormalViewMatrix,
  14939. highPrecisionModelViewMatrix: highPrecisionModelViewMatrix,
  14940. hue: hue,
  14941. instance: instance,
  14942. instanceIndex: instanceIndex,
  14943. instancedArray: instancedArray,
  14944. instancedBufferAttribute: instancedBufferAttribute,
  14945. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  14946. instancedMesh: instancedMesh,
  14947. int: int,
  14948. inverseSqrt: inverseSqrt,
  14949. invocationLocalIndex: invocationLocalIndex,
  14950. invocationSubgroupIndex: invocationSubgroupIndex,
  14951. ior: ior,
  14952. iridescence: iridescence,
  14953. iridescenceIOR: iridescenceIOR,
  14954. iridescenceThickness: iridescenceThickness,
  14955. ivec2: ivec2,
  14956. ivec3: ivec3,
  14957. ivec4: ivec4,
  14958. js: js,
  14959. label: label,
  14960. length: length,
  14961. lengthSq: lengthSq,
  14962. lessThan: lessThan,
  14963. lessThanEqual: lessThanEqual,
  14964. lightPosition: lightPosition,
  14965. lightProjectionUV: lightProjectionUV,
  14966. lightShadowMatrix: lightShadowMatrix,
  14967. lightTargetDirection: lightTargetDirection,
  14968. lightTargetPosition: lightTargetPosition,
  14969. lightViewPosition: lightViewPosition,
  14970. lightingContext: lightingContext,
  14971. lights: lights,
  14972. linearDepth: linearDepth,
  14973. linearToneMapping: linearToneMapping,
  14974. localId: localId,
  14975. log: log,
  14976. log2: log2,
  14977. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  14978. loop: loop,
  14979. luminance: luminance,
  14980. mat2: mat2,
  14981. mat3: mat3,
  14982. mat4: mat4,
  14983. matcapUV: matcapUV,
  14984. materialAOMap: materialAOMap,
  14985. materialAlphaTest: materialAlphaTest,
  14986. materialAnisotropy: materialAnisotropy,
  14987. materialAnisotropyVector: materialAnisotropyVector,
  14988. materialAttenuationColor: materialAttenuationColor,
  14989. materialAttenuationDistance: materialAttenuationDistance,
  14990. materialClearcoat: materialClearcoat,
  14991. materialClearcoatNormal: materialClearcoatNormal,
  14992. materialClearcoatRoughness: materialClearcoatRoughness,
  14993. materialColor: materialColor,
  14994. materialDispersion: materialDispersion,
  14995. materialEmissive: materialEmissive,
  14996. materialIOR: materialIOR,
  14997. materialIridescence: materialIridescence,
  14998. materialIridescenceIOR: materialIridescenceIOR,
  14999. materialIridescenceThickness: materialIridescenceThickness,
  15000. materialLightMap: materialLightMap,
  15001. materialLineDashOffset: materialLineDashOffset,
  15002. materialLineDashSize: materialLineDashSize,
  15003. materialLineGapSize: materialLineGapSize,
  15004. materialLineScale: materialLineScale,
  15005. materialLineWidth: materialLineWidth,
  15006. materialMetalness: materialMetalness,
  15007. materialNormal: materialNormal,
  15008. materialOpacity: materialOpacity,
  15009. materialPointWidth: materialPointWidth,
  15010. materialReference: materialReference,
  15011. materialReflectivity: materialReflectivity,
  15012. materialRefractionRatio: materialRefractionRatio,
  15013. materialRotation: materialRotation,
  15014. materialRoughness: materialRoughness,
  15015. materialSheen: materialSheen,
  15016. materialSheenRoughness: materialSheenRoughness,
  15017. materialShininess: materialShininess,
  15018. materialSpecular: materialSpecular,
  15019. materialSpecularColor: materialSpecularColor,
  15020. materialSpecularIntensity: materialSpecularIntensity,
  15021. materialSpecularStrength: materialSpecularStrength,
  15022. materialThickness: materialThickness,
  15023. materialTransmission: materialTransmission,
  15024. max: max$1,
  15025. maxMipLevel: maxMipLevel,
  15026. metalness: metalness,
  15027. min: min$1,
  15028. mix: mix,
  15029. mixElement: mixElement,
  15030. mod: mod,
  15031. modInt: modInt,
  15032. modelDirection: modelDirection,
  15033. modelNormalMatrix: modelNormalMatrix,
  15034. modelPosition: modelPosition,
  15035. modelScale: modelScale,
  15036. modelViewMatrix: modelViewMatrix,
  15037. modelViewPosition: modelViewPosition,
  15038. modelViewProjection: modelViewProjection,
  15039. modelWorldMatrix: modelWorldMatrix,
  15040. modelWorldMatrixInverse: modelWorldMatrixInverse,
  15041. morphReference: morphReference,
  15042. mrt: mrt,
  15043. mul: mul,
  15044. mx_aastep: mx_aastep,
  15045. mx_cell_noise_float: mx_cell_noise_float,
  15046. mx_contrast: mx_contrast,
  15047. mx_fractal_noise_float: mx_fractal_noise_float,
  15048. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  15049. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  15050. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  15051. mx_hsvtorgb: mx_hsvtorgb,
  15052. mx_noise_float: mx_noise_float,
  15053. mx_noise_vec3: mx_noise_vec3,
  15054. mx_noise_vec4: mx_noise_vec4,
  15055. mx_ramplr: mx_ramplr,
  15056. mx_ramptb: mx_ramptb,
  15057. mx_rgbtohsv: mx_rgbtohsv,
  15058. mx_safepower: mx_safepower,
  15059. mx_splitlr: mx_splitlr,
  15060. mx_splittb: mx_splittb,
  15061. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  15062. mx_transform_uv: mx_transform_uv,
  15063. mx_worley_noise_float: mx_worley_noise_float,
  15064. mx_worley_noise_vec2: mx_worley_noise_vec2,
  15065. mx_worley_noise_vec3: mx_worley_noise_vec3,
  15066. negate: negate,
  15067. neutralToneMapping: neutralToneMapping,
  15068. nodeArray: nodeArray,
  15069. nodeImmutable: nodeImmutable,
  15070. nodeObject: nodeObject,
  15071. nodeObjects: nodeObjects,
  15072. nodeProxy: nodeProxy,
  15073. normalFlat: normalFlat,
  15074. normalGeometry: normalGeometry,
  15075. normalLocal: normalLocal,
  15076. normalMap: normalMap,
  15077. normalView: normalView,
  15078. normalWorld: normalWorld,
  15079. normalize: normalize,
  15080. not: not,
  15081. notEqual: notEqual,
  15082. numWorkgroups: numWorkgroups,
  15083. objectDirection: objectDirection,
  15084. objectGroup: objectGroup,
  15085. objectPosition: objectPosition,
  15086. objectScale: objectScale,
  15087. objectViewPosition: objectViewPosition,
  15088. objectWorldMatrix: objectWorldMatrix,
  15089. oneMinus: oneMinus,
  15090. or: or,
  15091. orthographicDepthToViewZ: orthographicDepthToViewZ,
  15092. oscSawtooth: oscSawtooth,
  15093. oscSine: oscSine,
  15094. oscSquare: oscSquare,
  15095. oscTriangle: oscTriangle,
  15096. output: output,
  15097. outputStruct: outputStruct,
  15098. overlay: overlay,
  15099. overloadingFn: overloadingFn,
  15100. parabola: parabola,
  15101. parallaxDirection: parallaxDirection,
  15102. parallaxUV: parallaxUV,
  15103. parameter: parameter,
  15104. pass: pass,
  15105. passTexture: passTexture,
  15106. pcurve: pcurve,
  15107. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  15108. pmremTexture: pmremTexture,
  15109. pointUV: pointUV,
  15110. pointWidth: pointWidth,
  15111. positionGeometry: positionGeometry,
  15112. positionLocal: positionLocal,
  15113. positionPrevious: positionPrevious,
  15114. positionView: positionView,
  15115. positionViewDirection: positionViewDirection,
  15116. positionWorld: positionWorld,
  15117. positionWorldDirection: positionWorldDirection,
  15118. posterize: posterize,
  15119. pow: pow,
  15120. pow2: pow2,
  15121. pow3: pow3,
  15122. pow4: pow4,
  15123. property: property,
  15124. radians: radians,
  15125. rand: rand,
  15126. range: range,
  15127. rangeFog: rangeFog,
  15128. reciprocal: reciprocal,
  15129. reference: reference,
  15130. referenceBuffer: referenceBuffer,
  15131. reflect: reflect,
  15132. reflectVector: reflectVector,
  15133. reflectView: reflectView,
  15134. reflector: reflector,
  15135. refract: refract,
  15136. refractVector: refractVector,
  15137. refractView: refractView,
  15138. reinhardToneMapping: reinhardToneMapping,
  15139. remainder: remainder,
  15140. remap: remap,
  15141. remapClamp: remapClamp,
  15142. renderGroup: renderGroup,
  15143. renderOutput: renderOutput,
  15144. rendererReference: rendererReference,
  15145. rotate: rotate,
  15146. rotateUV: rotateUV,
  15147. roughness: roughness,
  15148. round: round,
  15149. rtt: rtt,
  15150. sRGBTransferEOTF: sRGBTransferEOTF,
  15151. sRGBTransferOETF: sRGBTransferOETF,
  15152. sampler: sampler,
  15153. saturate: saturate,
  15154. saturation: saturation,
  15155. screen: screen,
  15156. screenCoordinate: screenCoordinate,
  15157. screenSize: screenSize,
  15158. screenUV: screenUV,
  15159. scriptable: scriptable,
  15160. scriptableValue: scriptableValue,
  15161. select: select,
  15162. setCurrentStack: setCurrentStack,
  15163. shaderStages: shaderStages,
  15164. shadow: shadow,
  15165. sharedUniformGroup: sharedUniformGroup,
  15166. sheen: sheen,
  15167. sheenRoughness: sheenRoughness,
  15168. shiftLeft: shiftLeft,
  15169. shiftRight: shiftRight,
  15170. shininess: shininess,
  15171. sign: sign,
  15172. sin: sin,
  15173. sinc: sinc,
  15174. skinning: skinning,
  15175. skinningReference: skinningReference,
  15176. smoothstep: smoothstep,
  15177. smoothstepElement: smoothstepElement,
  15178. specularColor: specularColor,
  15179. specularF90: specularF90,
  15180. spherizeUV: spherizeUV,
  15181. split: split,
  15182. spritesheetUV: spritesheetUV,
  15183. sqrt: sqrt,
  15184. stack: stack,
  15185. step: step,
  15186. storage: storage,
  15187. storageBarrier: storageBarrier,
  15188. storageObject: storageObject,
  15189. storageTexture: storageTexture,
  15190. string: string,
  15191. sub: sub,
  15192. subgroupIndex: subgroupIndex,
  15193. subgroupSize: subgroupSize,
  15194. tan: tan,
  15195. tangentGeometry: tangentGeometry,
  15196. tangentLocal: tangentLocal,
  15197. tangentView: tangentView,
  15198. tangentWorld: tangentWorld,
  15199. temp: temp,
  15200. texture: texture,
  15201. texture3D: texture3D,
  15202. textureBarrier: textureBarrier,
  15203. textureBicubic: textureBicubic,
  15204. textureCubeUV: textureCubeUV,
  15205. textureLoad: textureLoad,
  15206. textureSize: textureSize,
  15207. textureStore: textureStore,
  15208. thickness: thickness,
  15209. threshold: threshold,
  15210. time: time,
  15211. timerDelta: timerDelta,
  15212. timerGlobal: timerGlobal,
  15213. timerLocal: timerLocal,
  15214. toOutputColorSpace: toOutputColorSpace,
  15215. toWorkingColorSpace: toWorkingColorSpace,
  15216. toneMapping: toneMapping,
  15217. toneMappingExposure: toneMappingExposure,
  15218. toonOutlinePass: toonOutlinePass,
  15219. transformDirection: transformDirection,
  15220. transformNormal: transformNormal,
  15221. transformNormalToView: transformNormalToView,
  15222. transformedBentNormalView: transformedBentNormalView,
  15223. transformedBitangentView: transformedBitangentView,
  15224. transformedBitangentWorld: transformedBitangentWorld,
  15225. transformedClearcoatNormalView: transformedClearcoatNormalView,
  15226. transformedNormalView: transformedNormalView,
  15227. transformedNormalWorld: transformedNormalWorld,
  15228. transformedTangentView: transformedTangentView,
  15229. transformedTangentWorld: transformedTangentWorld,
  15230. transmission: transmission,
  15231. transpose: transpose,
  15232. tri: tri,
  15233. tri3: tri3,
  15234. triNoise3D: triNoise3D,
  15235. triplanarTexture: triplanarTexture,
  15236. triplanarTextures: triplanarTextures,
  15237. trunc: trunc,
  15238. tslFn: tslFn,
  15239. uint: uint,
  15240. uniform: uniform,
  15241. uniformArray: uniformArray,
  15242. uniformGroup: uniformGroup,
  15243. uniforms: uniforms,
  15244. userData: userData,
  15245. uv: uv,
  15246. uvec2: uvec2,
  15247. uvec3: uvec3,
  15248. uvec4: uvec4,
  15249. varying: varying,
  15250. varyingProperty: varyingProperty,
  15251. vec2: vec2,
  15252. vec3: vec3,
  15253. vec4: vec4,
  15254. vectorComponents: vectorComponents,
  15255. velocity: velocity,
  15256. vertexColor: vertexColor,
  15257. vertexIndex: vertexIndex,
  15258. vibrance: vibrance,
  15259. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  15260. viewZToOrthographicDepth: viewZToOrthographicDepth,
  15261. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  15262. viewport: viewport,
  15263. viewportBottomLeft: viewportBottomLeft,
  15264. viewportCoordinate: viewportCoordinate,
  15265. viewportDepthTexture: viewportDepthTexture,
  15266. viewportLinearDepth: viewportLinearDepth,
  15267. viewportMipTexture: viewportMipTexture,
  15268. viewportResolution: viewportResolution,
  15269. viewportSafeUV: viewportSafeUV,
  15270. viewportSharedTexture: viewportSharedTexture,
  15271. viewportSize: viewportSize,
  15272. viewportTexture: viewportTexture,
  15273. viewportTopLeft: viewportTopLeft,
  15274. viewportUV: viewportUV,
  15275. wgsl: wgsl,
  15276. wgslFn: wgslFn,
  15277. workgroupArray: workgroupArray,
  15278. workgroupBarrier: workgroupBarrier,
  15279. workgroupId: workgroupId,
  15280. workingToColorSpace: workingToColorSpace,
  15281. xor: xor
  15282. });
  15283. const _clearColor$1 = /*@__PURE__*/ new Color4();
  15284. class Background extends DataMap {
  15285. constructor( renderer, nodes ) {
  15286. super();
  15287. this.renderer = renderer;
  15288. this.nodes = nodes;
  15289. }
  15290. update( scene, renderList, renderContext ) {
  15291. const renderer = this.renderer;
  15292. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  15293. let forceClear = false;
  15294. if ( background === null ) {
  15295. // no background settings, use clear color configuration from the renderer
  15296. renderer._clearColor.getRGB( _clearColor$1, LinearSRGBColorSpace );
  15297. _clearColor$1.a = renderer._clearColor.a;
  15298. } else if ( background.isColor === true ) {
  15299. // background is an opaque color
  15300. background.getRGB( _clearColor$1, LinearSRGBColorSpace );
  15301. _clearColor$1.a = 1;
  15302. forceClear = true;
  15303. } else if ( background.isNode === true ) {
  15304. const sceneData = this.get( scene );
  15305. const backgroundNode = background;
  15306. _clearColor$1.copy( renderer._clearColor );
  15307. let backgroundMesh = sceneData.backgroundMesh;
  15308. if ( backgroundMesh === undefined ) {
  15309. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  15310. // @TODO: Add Texture2D support using node context
  15311. getUV: () => backgroundRotation.mul( normalWorld ),
  15312. getTextureLevel: () => backgroundBlurriness
  15313. } );
  15314. let viewProj = modelViewProjection();
  15315. viewProj = viewProj.setZ( viewProj.w );
  15316. const nodeMaterial = new NodeMaterial();
  15317. nodeMaterial.name = 'Background.material';
  15318. nodeMaterial.side = BackSide;
  15319. nodeMaterial.depthTest = false;
  15320. nodeMaterial.depthWrite = false;
  15321. nodeMaterial.fog = false;
  15322. nodeMaterial.lights = false;
  15323. nodeMaterial.vertexNode = viewProj;
  15324. nodeMaterial.colorNode = backgroundMeshNode;
  15325. sceneData.backgroundMeshNode = backgroundMeshNode;
  15326. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  15327. backgroundMesh.frustumCulled = false;
  15328. backgroundMesh.name = 'Background.mesh';
  15329. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  15330. this.matrixWorld.copyPosition( camera.matrixWorld );
  15331. };
  15332. }
  15333. const backgroundCacheKey = backgroundNode.getCacheKey();
  15334. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  15335. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  15336. sceneData.backgroundMeshNode.needsUpdate = true;
  15337. backgroundMesh.material.needsUpdate = true;
  15338. sceneData.backgroundCacheKey = backgroundCacheKey;
  15339. }
  15340. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  15341. } else {
  15342. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  15343. }
  15344. //
  15345. if ( renderer.autoClear === true || forceClear === true ) {
  15346. const clearColorValue = renderContext.clearColorValue;
  15347. clearColorValue.r = _clearColor$1.r;
  15348. clearColorValue.g = _clearColor$1.g;
  15349. clearColorValue.b = _clearColor$1.b;
  15350. clearColorValue.a = _clearColor$1.a;
  15351. // premultiply alpha
  15352. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  15353. clearColorValue.r *= clearColorValue.a;
  15354. clearColorValue.g *= clearColorValue.a;
  15355. clearColorValue.b *= clearColorValue.a;
  15356. }
  15357. //
  15358. renderContext.depthClearValue = renderer._clearDepth;
  15359. renderContext.stencilClearValue = renderer._clearStencil;
  15360. renderContext.clearColor = renderer.autoClearColor === true;
  15361. renderContext.clearDepth = renderer.autoClearDepth === true;
  15362. renderContext.clearStencil = renderer.autoClearStencil === true;
  15363. } else {
  15364. renderContext.clearColor = false;
  15365. renderContext.clearDepth = false;
  15366. renderContext.clearStencil = false;
  15367. }
  15368. }
  15369. }
  15370. let _id$6 = 0;
  15371. class BindGroup {
  15372. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  15373. this.name = name;
  15374. this.bindings = bindings;
  15375. this.index = index;
  15376. this.bindingsReference = bindingsReference;
  15377. this.id = _id$6 ++;
  15378. }
  15379. }
  15380. class NodeBuilderState {
  15381. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, monitor, transforms = [] ) {
  15382. this.vertexShader = vertexShader;
  15383. this.fragmentShader = fragmentShader;
  15384. this.computeShader = computeShader;
  15385. this.transforms = transforms;
  15386. this.nodeAttributes = nodeAttributes;
  15387. this.bindings = bindings;
  15388. this.updateNodes = updateNodes;
  15389. this.updateBeforeNodes = updateBeforeNodes;
  15390. this.updateAfterNodes = updateAfterNodes;
  15391. this.monitor = monitor;
  15392. this.usedTimes = 0;
  15393. }
  15394. createBindings() {
  15395. const bindings = [];
  15396. for ( const instanceGroup of this.bindings ) {
  15397. const shared = instanceGroup.bindings[ 0 ].groupNode.shared;
  15398. if ( shared !== true ) {
  15399. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  15400. bindings.push( bindingsGroup );
  15401. for ( const instanceBinding of instanceGroup.bindings ) {
  15402. bindingsGroup.bindings.push( instanceBinding.clone() );
  15403. }
  15404. } else {
  15405. bindings.push( instanceGroup );
  15406. }
  15407. }
  15408. return bindings;
  15409. }
  15410. }
  15411. /**
  15412. * {@link NodeBuilder} is going to create instances of this class during the build process
  15413. * of nodes. They represent the final shader attributes that are going to be generated
  15414. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  15415. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  15416. */
  15417. class NodeAttribute {
  15418. /**
  15419. * Constructs a new node attribute.
  15420. *
  15421. * @param {String} name - The name of the attribute.
  15422. * @param {String} type - The type of the attribute.
  15423. * @param {Node?} node - An optional reference to the node.
  15424. */
  15425. constructor( name, type, node = null ) {
  15426. /**
  15427. * This flag can be used for type testing.
  15428. *
  15429. * @type {Boolean}
  15430. * @readonly
  15431. * @default true
  15432. */
  15433. this.isNodeAttribute = true;
  15434. /**
  15435. * The name of the attribute.
  15436. *
  15437. * @type {String}
  15438. */
  15439. this.name = name;
  15440. /**
  15441. * The type of the attribute.
  15442. *
  15443. * @type {String}
  15444. */
  15445. this.type = type;
  15446. /**
  15447. * An optional reference to the node.
  15448. *
  15449. * @type {Node?}
  15450. * @default null
  15451. */
  15452. this.node = node;
  15453. }
  15454. }
  15455. /**
  15456. * {@link NodeBuilder} is going to create instances of this class during the build process
  15457. * of nodes. They represent the final shader uniforms that are going to be generated
  15458. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  15459. * for this purpose.
  15460. */
  15461. class NodeUniform {
  15462. /**
  15463. * Constructs a new node uniform.
  15464. *
  15465. * @param {String} name - The name of the uniform.
  15466. * @param {String} type - The type of the uniform.
  15467. * @param {UniformNode} node - An reference to the node.
  15468. */
  15469. constructor( name, type, node ) {
  15470. /**
  15471. * This flag can be used for type testing.
  15472. *
  15473. * @type {Boolean}
  15474. * @readonly
  15475. * @default true
  15476. */
  15477. this.isNodeUniform = true;
  15478. /**
  15479. * The name of the uniform.
  15480. *
  15481. * @type {String}
  15482. */
  15483. this.name = name;
  15484. /**
  15485. * The type of the uniform.
  15486. *
  15487. * @type {String}
  15488. */
  15489. this.type = type;
  15490. /**
  15491. * An reference to the node.
  15492. *
  15493. * @type {UniformNode}
  15494. */
  15495. this.node = node.getSelf();
  15496. }
  15497. /**
  15498. * The value of the uniform node.
  15499. *
  15500. * @type {Any}
  15501. */
  15502. get value() {
  15503. return this.node.value;
  15504. }
  15505. set value( val ) {
  15506. this.node.value = val;
  15507. }
  15508. /**
  15509. * The id of the uniform node.
  15510. *
  15511. * @type {Number}
  15512. */
  15513. get id() {
  15514. return this.node.id;
  15515. }
  15516. /**
  15517. * The uniform node's group.
  15518. *
  15519. * @type {UniformGroupNode}
  15520. */
  15521. get groupNode() {
  15522. return this.node.groupNode;
  15523. }
  15524. }
  15525. /**
  15526. * {@link NodeBuilder} is going to create instances of this class during the build process
  15527. * of nodes. They represent the final shader variables that are going to be generated
  15528. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  15529. * this purpose.
  15530. */
  15531. class NodeVar {
  15532. /**
  15533. * Constructs a new node variable.
  15534. *
  15535. * @param {String} name - The name of the variable.
  15536. * @param {String} type - The type of the variable.
  15537. */
  15538. constructor( name, type ) {
  15539. /**
  15540. * This flag can be used for type testing.
  15541. *
  15542. * @type {Boolean}
  15543. * @readonly
  15544. * @default true
  15545. */
  15546. this.isNodeVar = true;
  15547. /**
  15548. * The name of the variable.
  15549. *
  15550. * @type {String}
  15551. */
  15552. this.name = name;
  15553. /**
  15554. * The type of the variable.
  15555. *
  15556. * @type {String}
  15557. */
  15558. this.type = type;
  15559. }
  15560. }
  15561. /**
  15562. * {@link NodeBuilder} is going to create instances of this class during the build process
  15563. * of nodes. They represent the final shader varyings that are going to be generated
  15564. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  15565. * this purpose.
  15566. *
  15567. * @augments NodeVar
  15568. */
  15569. class NodeVarying extends NodeVar {
  15570. /**
  15571. * Constructs a new node varying.
  15572. *
  15573. * @param {String} name - The name of the varying.
  15574. * @param {String} type - The type of the varying.
  15575. */
  15576. constructor( name, type ) {
  15577. super( name, type );
  15578. /**
  15579. * Whether this varying requires interpolation or not. This property can be used
  15580. * to check if the varying can be optimized for a variable.
  15581. *
  15582. * @type {Boolean}
  15583. * @default false
  15584. */
  15585. this.needsInterpolation = false;
  15586. /**
  15587. * This flag can be used for type testing.
  15588. *
  15589. * @type {Boolean}
  15590. * @readonly
  15591. * @default true
  15592. */
  15593. this.isNodeVarying = true;
  15594. }
  15595. }
  15596. /**
  15597. * {@link NodeBuilder} is going to create instances of this class during the build process
  15598. * of nodes. They represent user-defined, native shader code portions that are going to be
  15599. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  15600. * for this purpose.
  15601. */
  15602. class NodeCode {
  15603. /**
  15604. * Constructs a new code node.
  15605. *
  15606. * @param {String} name - The name of the code.
  15607. * @param {String} type - The node type.
  15608. * @param {String} [code=''] - The native shader code.
  15609. */
  15610. constructor( name, type, code = '' ) {
  15611. /**
  15612. * The name of the code.
  15613. *
  15614. * @type {String}
  15615. */
  15616. this.name = name;
  15617. /**
  15618. * The node type.
  15619. *
  15620. * @type {String}
  15621. */
  15622. this.type = type;
  15623. /**
  15624. * The native shader code.
  15625. *
  15626. * @type {String}
  15627. * @default ''
  15628. */
  15629. this.code = code;
  15630. Object.defineProperty( this, 'isNodeCode', { value: true } );
  15631. }
  15632. }
  15633. let _id$5 = 0;
  15634. /**
  15635. * This utility class is used in {@link NodeBuilder} as an internal
  15636. * cache data structure for node data.
  15637. */
  15638. class NodeCache {
  15639. /**
  15640. * Constructs a new node cache.
  15641. *
  15642. * @param {NodeCache?} parent - A reference to a parent cache.
  15643. */
  15644. constructor( parent = null ) {
  15645. /**
  15646. * The id of the cache.
  15647. *
  15648. * @type {Number}
  15649. * @readonly
  15650. */
  15651. this.id = _id$5 ++;
  15652. /**
  15653. * A weak map for managing node data.
  15654. *
  15655. * @type {WeakMap}
  15656. */
  15657. this.nodesData = new WeakMap();
  15658. /**
  15659. * Reference to a parent node cache.
  15660. *
  15661. * @type {NodeCache?}
  15662. * @default null
  15663. */
  15664. this.parent = parent;
  15665. }
  15666. /**
  15667. * Returns the data for the given node.
  15668. *
  15669. * @param {Node} node - The node.
  15670. * @return {Object?} The data for the node.
  15671. */
  15672. getData( node ) {
  15673. let data = this.nodesData.get( node );
  15674. if ( data === undefined && this.parent !== null ) {
  15675. data = this.parent.getData( node );
  15676. }
  15677. return data;
  15678. }
  15679. /**
  15680. * Sets the data for a given node.
  15681. *
  15682. * @param {Node} node - The node.
  15683. * @param {Object} data - The data that should be cached.
  15684. */
  15685. setData( node, data ) {
  15686. this.nodesData.set( node, data );
  15687. }
  15688. }
  15689. /**
  15690. * {@link NodeBuilder} is going to create instances of this class during the build process
  15691. * of nodes. They represent the final shader struct data that are going to be generated
  15692. * by the builder. A dictionary of struct types is maintained in {@link NodeBuilder#structs}
  15693. * for this purpose.
  15694. */
  15695. class StructTypeNode extends Node {
  15696. static get type() {
  15697. return 'StructTypeNode';
  15698. }
  15699. /**
  15700. * Constructs a new struct type node.
  15701. *
  15702. * @param {String} name - The name of the struct.
  15703. * @param {Array<String>} types - An array of types.
  15704. */
  15705. constructor( name, types ) {
  15706. super();
  15707. /**
  15708. * The name of the struct.
  15709. *
  15710. * @type {String}
  15711. */
  15712. this.name = name;
  15713. /**
  15714. * An array of types.
  15715. *
  15716. * @type {Array<String>}
  15717. */
  15718. this.types = types;
  15719. /**
  15720. * This flag can be used for type testing.
  15721. *
  15722. * @type {Boolean}
  15723. * @readonly
  15724. * @default true
  15725. */
  15726. this.isStructTypeNode = true;
  15727. }
  15728. /**
  15729. * Returns the member types.
  15730. *
  15731. * @return {Array<String>} The types.
  15732. */
  15733. getMemberTypes() {
  15734. return this.types;
  15735. }
  15736. }
  15737. class Uniform {
  15738. constructor( name, value ) {
  15739. this.name = name;
  15740. this.value = value;
  15741. this.boundary = 0; // used to build the uniform buffer according to the STD140 layout
  15742. this.itemSize = 0;
  15743. this.offset = 0; // this property is set by WebGPUUniformsGroup and marks the start position in the uniform buffer
  15744. }
  15745. setValue( value ) {
  15746. this.value = value;
  15747. }
  15748. getValue() {
  15749. return this.value;
  15750. }
  15751. }
  15752. class NumberUniform extends Uniform {
  15753. constructor( name, value = 0 ) {
  15754. super( name, value );
  15755. this.isNumberUniform = true;
  15756. this.boundary = 4;
  15757. this.itemSize = 1;
  15758. }
  15759. }
  15760. class Vector2Uniform extends Uniform {
  15761. constructor( name, value = new Vector2() ) {
  15762. super( name, value );
  15763. this.isVector2Uniform = true;
  15764. this.boundary = 8;
  15765. this.itemSize = 2;
  15766. }
  15767. }
  15768. class Vector3Uniform extends Uniform {
  15769. constructor( name, value = new Vector3() ) {
  15770. super( name, value );
  15771. this.isVector3Uniform = true;
  15772. this.boundary = 16;
  15773. this.itemSize = 3;
  15774. }
  15775. }
  15776. class Vector4Uniform extends Uniform {
  15777. constructor( name, value = new Vector4() ) {
  15778. super( name, value );
  15779. this.isVector4Uniform = true;
  15780. this.boundary = 16;
  15781. this.itemSize = 4;
  15782. }
  15783. }
  15784. class ColorUniform extends Uniform {
  15785. constructor( name, value = new Color() ) {
  15786. super( name, value );
  15787. this.isColorUniform = true;
  15788. this.boundary = 16;
  15789. this.itemSize = 3;
  15790. }
  15791. }
  15792. class Matrix3Uniform extends Uniform {
  15793. constructor( name, value = new Matrix3() ) {
  15794. super( name, value );
  15795. this.isMatrix3Uniform = true;
  15796. this.boundary = 48;
  15797. this.itemSize = 12;
  15798. }
  15799. }
  15800. class Matrix4Uniform extends Uniform {
  15801. constructor( name, value = new Matrix4() ) {
  15802. super( name, value );
  15803. this.isMatrix4Uniform = true;
  15804. this.boundary = 64;
  15805. this.itemSize = 16;
  15806. }
  15807. }
  15808. class NumberNodeUniform extends NumberUniform {
  15809. constructor( nodeUniform ) {
  15810. super( nodeUniform.name, nodeUniform.value );
  15811. this.nodeUniform = nodeUniform;
  15812. }
  15813. getValue() {
  15814. return this.nodeUniform.value;
  15815. }
  15816. getType() {
  15817. return this.nodeUniform.type;
  15818. }
  15819. }
  15820. class Vector2NodeUniform extends Vector2Uniform {
  15821. constructor( nodeUniform ) {
  15822. super( nodeUniform.name, nodeUniform.value );
  15823. this.nodeUniform = nodeUniform;
  15824. }
  15825. getValue() {
  15826. return this.nodeUniform.value;
  15827. }
  15828. getType() {
  15829. return this.nodeUniform.type;
  15830. }
  15831. }
  15832. class Vector3NodeUniform extends Vector3Uniform {
  15833. constructor( nodeUniform ) {
  15834. super( nodeUniform.name, nodeUniform.value );
  15835. this.nodeUniform = nodeUniform;
  15836. }
  15837. getValue() {
  15838. return this.nodeUniform.value;
  15839. }
  15840. getType() {
  15841. return this.nodeUniform.type;
  15842. }
  15843. }
  15844. class Vector4NodeUniform extends Vector4Uniform {
  15845. constructor( nodeUniform ) {
  15846. super( nodeUniform.name, nodeUniform.value );
  15847. this.nodeUniform = nodeUniform;
  15848. }
  15849. getValue() {
  15850. return this.nodeUniform.value;
  15851. }
  15852. getType() {
  15853. return this.nodeUniform.type;
  15854. }
  15855. }
  15856. class ColorNodeUniform extends ColorUniform {
  15857. constructor( nodeUniform ) {
  15858. super( nodeUniform.name, nodeUniform.value );
  15859. this.nodeUniform = nodeUniform;
  15860. }
  15861. getValue() {
  15862. return this.nodeUniform.value;
  15863. }
  15864. getType() {
  15865. return this.nodeUniform.type;
  15866. }
  15867. }
  15868. class Matrix3NodeUniform extends Matrix3Uniform {
  15869. constructor( nodeUniform ) {
  15870. super( nodeUniform.name, nodeUniform.value );
  15871. this.nodeUniform = nodeUniform;
  15872. }
  15873. getValue() {
  15874. return this.nodeUniform.value;
  15875. }
  15876. getType() {
  15877. return this.nodeUniform.type;
  15878. }
  15879. }
  15880. class Matrix4NodeUniform extends Matrix4Uniform {
  15881. constructor( nodeUniform ) {
  15882. super( nodeUniform.name, nodeUniform.value );
  15883. this.nodeUniform = nodeUniform;
  15884. }
  15885. getValue() {
  15886. return this.nodeUniform.value;
  15887. }
  15888. getType() {
  15889. return this.nodeUniform.type;
  15890. }
  15891. }
  15892. const LOD_MIN = 4;
  15893. // The standard deviations (radians) associated with the extra mips. These are
  15894. // chosen to approximate a Trowbridge-Reitz distribution function times the
  15895. // geometric shadowing function. These sigma values squared must match the
  15896. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  15897. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  15898. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  15899. // samples and exit early, but not recompile the shader.
  15900. const MAX_SAMPLES = 20;
  15901. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  15902. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  15903. const _clearColor = /*@__PURE__*/ new Color();
  15904. let _oldTarget = null;
  15905. let _oldActiveCubeFace = 0;
  15906. let _oldActiveMipmapLevel = 0;
  15907. // Golden Ratio
  15908. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  15909. const INV_PHI = 1 / PHI;
  15910. // Vertices of a dodecahedron (except the opposites, which represent the
  15911. // same axis), used as axis directions evenly spread on a sphere.
  15912. const _axisDirections = [
  15913. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  15914. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  15915. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  15916. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  15917. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  15918. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  15919. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  15920. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  15921. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  15922. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  15923. ];
  15924. //
  15925. // WebGPU Face indices
  15926. const _faceLib = [
  15927. 3, 1, 5,
  15928. 0, 4, 2
  15929. ];
  15930. const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  15931. const outputDirection = vec3( direction.x, direction.y.negate(), direction.z );
  15932. /**
  15933. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  15934. * (PMREM) from a cubeMap environment texture. This allows different levels of
  15935. * blur to be quickly accessed based on material roughness. It is packed into a
  15936. * special CubeUV format that allows us to perform custom interpolation so that
  15937. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  15938. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  15939. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  15940. * higher roughness levels. In this way we maintain resolution to smoothly
  15941. * interpolate diffuse lighting while limiting sampling computation.
  15942. *
  15943. * Paper: Fast, Accurate Image-Based Lighting
  15944. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  15945. */
  15946. class PMREMGenerator {
  15947. constructor( renderer ) {
  15948. this._renderer = renderer;
  15949. this._pingPongRenderTarget = null;
  15950. this._lodMax = 0;
  15951. this._cubeSize = 0;
  15952. this._lodPlanes = [];
  15953. this._sizeLods = [];
  15954. this._sigmas = [];
  15955. this._lodMeshes = [];
  15956. this._blurMaterial = null;
  15957. this._cubemapMaterial = null;
  15958. this._equirectMaterial = null;
  15959. this._backgroundBox = null;
  15960. }
  15961. get _hasInitialized() {
  15962. return this._renderer.hasInitialized();
  15963. }
  15964. /**
  15965. * Generates a PMREM from a supplied Scene, which can be faster than using an
  15966. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  15967. * in radians to be applied to the scene before PMREM generation. Optional near
  15968. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  15969. * is placed at the origin).
  15970. */
  15971. fromScene( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  15972. this._setSize( 256 );
  15973. if ( this._hasInitialized === false ) {
  15974. console.warn( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  15975. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  15976. this.fromSceneAsync( scene, sigma, near, far, cubeUVRenderTarget );
  15977. return cubeUVRenderTarget;
  15978. }
  15979. _oldTarget = this._renderer.getRenderTarget();
  15980. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  15981. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  15982. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  15983. cubeUVRenderTarget.depthBuffer = true;
  15984. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  15985. if ( sigma > 0 ) {
  15986. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  15987. }
  15988. this._applyPMREM( cubeUVRenderTarget );
  15989. this._cleanup( cubeUVRenderTarget );
  15990. return cubeUVRenderTarget;
  15991. }
  15992. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  15993. if ( this._hasInitialized === false ) await this._renderer.init();
  15994. return this.fromScene( scene, sigma, near, far, renderTarget );
  15995. }
  15996. /**
  15997. * Generates a PMREM from an equirectangular texture, which can be either LDR
  15998. * or HDR. The ideal input image size is 1k (1024 x 512),
  15999. * as this matches best with the 256 x 256 cubemap output.
  16000. */
  16001. fromEquirectangular( equirectangular, renderTarget = null ) {
  16002. if ( this._hasInitialized === false ) {
  16003. console.warn( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  16004. this._setSizeFromTexture( equirectangular );
  16005. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  16006. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  16007. return cubeUVRenderTarget;
  16008. }
  16009. return this._fromTexture( equirectangular, renderTarget );
  16010. }
  16011. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  16012. if ( this._hasInitialized === false ) await this._renderer.init();
  16013. return this._fromTexture( equirectangular, renderTarget );
  16014. }
  16015. /**
  16016. * Generates a PMREM from an cubemap texture, which can be either LDR
  16017. * or HDR. The ideal input cube size is 256 x 256,
  16018. * as this matches best with the 256 x 256 cubemap output.
  16019. */
  16020. fromCubemap( cubemap, renderTarget = null ) {
  16021. if ( this._hasInitialized === false ) {
  16022. console.warn( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  16023. this._setSizeFromTexture( cubemap );
  16024. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  16025. this.fromCubemapAsync( cubemap, renderTarget );
  16026. return cubeUVRenderTarget;
  16027. }
  16028. return this._fromTexture( cubemap, renderTarget );
  16029. }
  16030. async fromCubemapAsync( cubemap, renderTarget = null ) {
  16031. if ( this._hasInitialized === false ) await this._renderer.init();
  16032. return this._fromTexture( cubemap, renderTarget );
  16033. }
  16034. /**
  16035. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  16036. * your texture's network fetch for increased concurrency.
  16037. */
  16038. async compileCubemapShader() {
  16039. if ( this._cubemapMaterial === null ) {
  16040. this._cubemapMaterial = _getCubemapMaterial();
  16041. await this._compileMaterial( this._cubemapMaterial );
  16042. }
  16043. }
  16044. /**
  16045. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  16046. * your texture's network fetch for increased concurrency.
  16047. */
  16048. async compileEquirectangularShader() {
  16049. if ( this._equirectMaterial === null ) {
  16050. this._equirectMaterial = _getEquirectMaterial();
  16051. await this._compileMaterial( this._equirectMaterial );
  16052. }
  16053. }
  16054. /**
  16055. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  16056. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  16057. * one of them will cause any others to also become unusable.
  16058. */
  16059. dispose() {
  16060. this._dispose();
  16061. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  16062. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  16063. if ( this._backgroundBox !== null ) {
  16064. this._backgroundBox.geometry.dispose();
  16065. this._backgroundBox.material.dispose();
  16066. }
  16067. }
  16068. // private interface
  16069. _setSizeFromTexture( texture ) {
  16070. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  16071. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  16072. } else { // Equirectangular
  16073. this._setSize( texture.image.width / 4 );
  16074. }
  16075. }
  16076. _setSize( cubeSize ) {
  16077. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  16078. this._cubeSize = Math.pow( 2, this._lodMax );
  16079. }
  16080. _dispose() {
  16081. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  16082. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  16083. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  16084. this._lodPlanes[ i ].dispose();
  16085. }
  16086. }
  16087. _cleanup( outputTarget ) {
  16088. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  16089. outputTarget.scissorTest = false;
  16090. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  16091. }
  16092. _fromTexture( texture, renderTarget ) {
  16093. this._setSizeFromTexture( texture );
  16094. _oldTarget = this._renderer.getRenderTarget();
  16095. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  16096. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  16097. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  16098. this._textureToCubeUV( texture, cubeUVRenderTarget );
  16099. this._applyPMREM( cubeUVRenderTarget );
  16100. this._cleanup( cubeUVRenderTarget );
  16101. return cubeUVRenderTarget;
  16102. }
  16103. _allocateTargets() {
  16104. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  16105. const height = 4 * this._cubeSize;
  16106. const params = {
  16107. magFilter: LinearFilter,
  16108. minFilter: LinearFilter,
  16109. generateMipmaps: false,
  16110. type: HalfFloatType,
  16111. format: RGBAFormat,
  16112. colorSpace: LinearSRGBColorSpace,
  16113. //depthBuffer: false
  16114. };
  16115. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  16116. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  16117. if ( this._pingPongRenderTarget !== null ) {
  16118. this._dispose();
  16119. }
  16120. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  16121. const { _lodMax } = this;
  16122. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  16123. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  16124. }
  16125. return cubeUVRenderTarget;
  16126. }
  16127. async _compileMaterial( material ) {
  16128. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  16129. await this._renderer.compile( tmpMesh, _flatCamera );
  16130. }
  16131. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  16132. const cubeCamera = _cubeCamera;
  16133. cubeCamera.near = near;
  16134. cubeCamera.far = far;
  16135. // px, py, pz, nx, ny, nz
  16136. const upSign = [ - 1, 1, - 1, - 1, - 1, - 1 ];
  16137. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  16138. const renderer = this._renderer;
  16139. const originalAutoClear = renderer.autoClear;
  16140. renderer.getClearColor( _clearColor );
  16141. renderer.autoClear = false;
  16142. let backgroundBox = this._backgroundBox;
  16143. if ( backgroundBox === null ) {
  16144. const backgroundMaterial = new MeshBasicMaterial( {
  16145. name: 'PMREM.Background',
  16146. side: BackSide,
  16147. depthWrite: false,
  16148. depthTest: false
  16149. } );
  16150. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  16151. }
  16152. let useSolidColor = false;
  16153. const background = scene.background;
  16154. if ( background ) {
  16155. if ( background.isColor ) {
  16156. backgroundBox.material.color.copy( background );
  16157. scene.background = null;
  16158. useSolidColor = true;
  16159. }
  16160. } else {
  16161. backgroundBox.material.color.copy( _clearColor );
  16162. useSolidColor = true;
  16163. }
  16164. renderer.setRenderTarget( cubeUVRenderTarget );
  16165. renderer.clear();
  16166. if ( useSolidColor ) {
  16167. renderer.render( backgroundBox, cubeCamera );
  16168. }
  16169. for ( let i = 0; i < 6; i ++ ) {
  16170. const col = i % 3;
  16171. if ( col === 0 ) {
  16172. cubeCamera.up.set( 0, upSign[ i ], 0 );
  16173. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  16174. } else if ( col === 1 ) {
  16175. cubeCamera.up.set( 0, 0, upSign[ i ] );
  16176. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  16177. } else {
  16178. cubeCamera.up.set( 0, upSign[ i ], 0 );
  16179. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  16180. }
  16181. const size = this._cubeSize;
  16182. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  16183. renderer.render( scene, cubeCamera );
  16184. }
  16185. renderer.autoClear = originalAutoClear;
  16186. scene.background = background;
  16187. }
  16188. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  16189. const renderer = this._renderer;
  16190. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  16191. if ( isCubeTexture ) {
  16192. if ( this._cubemapMaterial === null ) {
  16193. this._cubemapMaterial = _getCubemapMaterial( texture );
  16194. }
  16195. } else {
  16196. if ( this._equirectMaterial === null ) {
  16197. this._equirectMaterial = _getEquirectMaterial( texture );
  16198. }
  16199. }
  16200. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  16201. material.fragmentNode.value = texture;
  16202. const mesh = this._lodMeshes[ 0 ];
  16203. mesh.material = material;
  16204. const size = this._cubeSize;
  16205. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  16206. renderer.setRenderTarget( cubeUVRenderTarget );
  16207. renderer.render( mesh, _flatCamera );
  16208. }
  16209. _applyPMREM( cubeUVRenderTarget ) {
  16210. const renderer = this._renderer;
  16211. const autoClear = renderer.autoClear;
  16212. renderer.autoClear = false;
  16213. const n = this._lodPlanes.length;
  16214. for ( let i = 1; i < n; i ++ ) {
  16215. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  16216. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  16217. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  16218. }
  16219. renderer.autoClear = autoClear;
  16220. }
  16221. /**
  16222. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  16223. * vertically and horizontally, but this breaks down on a cube. Here we apply
  16224. * the blur latitudinally (around the poles), and then longitudinally (towards
  16225. * the poles) to approximate the orthogonally-separable blur. It is least
  16226. * accurate at the poles, but still does a decent job.
  16227. */
  16228. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  16229. const pingPongRenderTarget = this._pingPongRenderTarget;
  16230. this._halfBlur(
  16231. cubeUVRenderTarget,
  16232. pingPongRenderTarget,
  16233. lodIn,
  16234. lodOut,
  16235. sigma,
  16236. 'latitudinal',
  16237. poleAxis );
  16238. this._halfBlur(
  16239. pingPongRenderTarget,
  16240. cubeUVRenderTarget,
  16241. lodOut,
  16242. lodOut,
  16243. sigma,
  16244. 'longitudinal',
  16245. poleAxis );
  16246. }
  16247. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  16248. const renderer = this._renderer;
  16249. const blurMaterial = this._blurMaterial;
  16250. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  16251. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  16252. }
  16253. // Number of standard deviations at which to cut off the discrete approximation.
  16254. const STANDARD_DEVIATIONS = 3;
  16255. const blurMesh = this._lodMeshes[ lodOut ];
  16256. blurMesh.material = blurMaterial;
  16257. const blurUniforms = blurMaterial.uniforms;
  16258. const pixels = this._sizeLods[ lodIn ] - 1;
  16259. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  16260. const sigmaPixels = sigmaRadians / radiansPerPixel;
  16261. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  16262. if ( samples > MAX_SAMPLES ) {
  16263. console.warn( `sigmaRadians, ${
  16264. sigmaRadians}, is too large and will clip, as it requested ${
  16265. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  16266. }
  16267. const weights = [];
  16268. let sum = 0;
  16269. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  16270. const x = i / sigmaPixels;
  16271. const weight = Math.exp( - x * x / 2 );
  16272. weights.push( weight );
  16273. if ( i === 0 ) {
  16274. sum += weight;
  16275. } else if ( i < samples ) {
  16276. sum += 2 * weight;
  16277. }
  16278. }
  16279. for ( let i = 0; i < weights.length; i ++ ) {
  16280. weights[ i ] = weights[ i ] / sum;
  16281. }
  16282. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  16283. blurUniforms.envMap.value = targetIn.texture;
  16284. blurUniforms.samples.value = samples;
  16285. blurUniforms.weights.array = weights;
  16286. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  16287. if ( poleAxis ) {
  16288. blurUniforms.poleAxis.value = poleAxis;
  16289. }
  16290. const { _lodMax } = this;
  16291. blurUniforms.dTheta.value = radiansPerPixel;
  16292. blurUniforms.mipInt.value = _lodMax - lodIn;
  16293. const outputSize = this._sizeLods[ lodOut ];
  16294. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  16295. const y = 4 * ( this._cubeSize - outputSize );
  16296. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  16297. renderer.setRenderTarget( targetOut );
  16298. renderer.render( blurMesh, _flatCamera );
  16299. }
  16300. }
  16301. function _createPlanes( lodMax ) {
  16302. const lodPlanes = [];
  16303. const sizeLods = [];
  16304. const sigmas = [];
  16305. const lodMeshes = [];
  16306. let lod = lodMax;
  16307. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  16308. for ( let i = 0; i < totalLods; i ++ ) {
  16309. const sizeLod = Math.pow( 2, lod );
  16310. sizeLods.push( sizeLod );
  16311. let sigma = 1.0 / sizeLod;
  16312. if ( i > lodMax - LOD_MIN ) {
  16313. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  16314. } else if ( i === 0 ) {
  16315. sigma = 0;
  16316. }
  16317. sigmas.push( sigma );
  16318. const texelSize = 1.0 / ( sizeLod - 2 );
  16319. const min = - texelSize;
  16320. const max = 1 + texelSize;
  16321. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  16322. const cubeFaces = 6;
  16323. const vertices = 6;
  16324. const positionSize = 3;
  16325. const uvSize = 2;
  16326. const faceIndexSize = 1;
  16327. const position = new Float32Array( positionSize * vertices * cubeFaces );
  16328. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  16329. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  16330. for ( let face = 0; face < cubeFaces; face ++ ) {
  16331. const x = ( face % 3 ) * 2 / 3 - 1;
  16332. const y = face > 2 ? 0 : - 1;
  16333. const coordinates = [
  16334. x, y, 0,
  16335. x + 2 / 3, y, 0,
  16336. x + 2 / 3, y + 1, 0,
  16337. x, y, 0,
  16338. x + 2 / 3, y + 1, 0,
  16339. x, y + 1, 0
  16340. ];
  16341. const faceIdx = _faceLib[ face ];
  16342. position.set( coordinates, positionSize * vertices * faceIdx );
  16343. uv.set( uv1, uvSize * vertices * faceIdx );
  16344. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  16345. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  16346. }
  16347. const planes = new BufferGeometry();
  16348. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  16349. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  16350. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  16351. lodPlanes.push( planes );
  16352. lodMeshes.push( new Mesh( planes, null ) );
  16353. if ( lod > LOD_MIN ) {
  16354. lod --;
  16355. }
  16356. }
  16357. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  16358. }
  16359. function _createRenderTarget( width, height, params ) {
  16360. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  16361. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  16362. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  16363. cubeUVRenderTarget.texture.isPMREMTexture = true;
  16364. cubeUVRenderTarget.scissorTest = true;
  16365. return cubeUVRenderTarget;
  16366. }
  16367. function _setViewport( target, x, y, width, height ) {
  16368. target.viewport.set( x, y, width, height );
  16369. target.scissor.set( x, y, width, height );
  16370. }
  16371. function _getMaterial( type ) {
  16372. const material = new NodeMaterial();
  16373. material.depthTest = false;
  16374. material.depthWrite = false;
  16375. material.blending = NoBlending;
  16376. material.name = `PMREM_${ type }`;
  16377. return material;
  16378. }
  16379. function _getBlurShader( lodMax, width, height ) {
  16380. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  16381. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  16382. const dTheta = uniform( 0 );
  16383. const n = float( MAX_SAMPLES );
  16384. const latitudinal = uniform( 0 ); // false, bool
  16385. const samples = uniform( 1 ); // int
  16386. const envMap = texture( null );
  16387. const mipInt = uniform( 0 ); // int
  16388. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  16389. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  16390. const CUBEUV_MAX_MIP = float( lodMax );
  16391. const materialUniforms = {
  16392. n,
  16393. latitudinal,
  16394. weights,
  16395. poleAxis,
  16396. outputDirection,
  16397. dTheta,
  16398. samples,
  16399. envMap,
  16400. mipInt,
  16401. CUBEUV_TEXEL_WIDTH,
  16402. CUBEUV_TEXEL_HEIGHT,
  16403. CUBEUV_MAX_MIP
  16404. };
  16405. const material = _getMaterial( 'blur' );
  16406. material.uniforms = materialUniforms; // TODO: Move to outside of the material
  16407. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  16408. return material;
  16409. }
  16410. function _getCubemapMaterial( envTexture ) {
  16411. const material = _getMaterial( 'cubemap' );
  16412. material.fragmentNode = cubeTexture( envTexture, outputDirection );
  16413. return material;
  16414. }
  16415. function _getEquirectMaterial( envTexture ) {
  16416. const material = _getMaterial( 'equirect' );
  16417. material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 );
  16418. return material;
  16419. }
  16420. const rendererCache = new WeakMap();
  16421. const typeFromArray = new Map( [
  16422. [ Int8Array, 'int' ],
  16423. [ Int16Array, 'int' ],
  16424. [ Int32Array, 'int' ],
  16425. [ Uint8Array, 'uint' ],
  16426. [ Uint16Array, 'uint' ],
  16427. [ Uint32Array, 'uint' ],
  16428. [ Float32Array, 'float' ]
  16429. ] );
  16430. const toFloat = ( value ) => {
  16431. if ( /e/g.test( value ) ) {
  16432. return String( value ).replace( /\+/g, '' );
  16433. } else {
  16434. value = Number( value );
  16435. return value + ( value % 1 ? '' : '.0' );
  16436. }
  16437. };
  16438. /**
  16439. * Base class for builders which generate a shader program based
  16440. * on a 3D object and its node material definition.
  16441. */
  16442. class NodeBuilder {
  16443. /**
  16444. * Constructs a new node builder.
  16445. *
  16446. * @param {Object3D} object - The 3D object.
  16447. * @param {Renderer} renderer - The current renderer.
  16448. * @param {NodeParser} parser - A reference to a node parser.
  16449. */
  16450. constructor( object, renderer, parser ) {
  16451. /**
  16452. * The 3D object.
  16453. *
  16454. * @type {Object3D}
  16455. */
  16456. this.object = object;
  16457. /**
  16458. * The material of the 3D object.
  16459. *
  16460. * @type {Material?}
  16461. */
  16462. this.material = ( object && object.material ) || null;
  16463. /**
  16464. * The geometry of the 3D object.
  16465. *
  16466. * @type {BufferGeometry?}
  16467. */
  16468. this.geometry = ( object && object.geometry ) || null;
  16469. /**
  16470. * The current renderer.
  16471. *
  16472. * @type {Renderer}
  16473. */
  16474. this.renderer = renderer;
  16475. /**
  16476. * A reference to a node parser.
  16477. *
  16478. * @type {NodeParser}
  16479. */
  16480. this.parser = parser;
  16481. /**
  16482. * The scene the 3D object belongs to.
  16483. *
  16484. * @type {Scene?}
  16485. */
  16486. this.scene = null;
  16487. /**
  16488. * The camera the 3D object is rendered with.
  16489. *
  16490. * @type {Camera?}
  16491. */
  16492. this.camera = null;
  16493. this.nodes = [];
  16494. this.sequentialNodes = [];
  16495. this.updateNodes = [];
  16496. this.updateBeforeNodes = [];
  16497. this.updateAfterNodes = [];
  16498. this.hashNodes = {};
  16499. this.monitor = null;
  16500. this.lightsNode = null;
  16501. this.environmentNode = null;
  16502. this.fogNode = null;
  16503. this.clippingContext = null;
  16504. this.vertexShader = null;
  16505. this.fragmentShader = null;
  16506. this.computeShader = null;
  16507. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  16508. this.flowCode = { vertex: '', fragment: '', compute: '' };
  16509. /**
  16510. * This dictionary holds the node uniforms of the builder.
  16511. * The uniforms are maintained in an array for each shader stage.
  16512. *
  16513. * @type {Object}
  16514. */
  16515. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  16516. /**
  16517. * This dictionary holds the output structs of the builder.
  16518. * The structs are maintained in an array for each shader stage.
  16519. *
  16520. * @type {Object}
  16521. */
  16522. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  16523. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  16524. this.bindingsIndexes = {};
  16525. this.bindGroups = null;
  16526. /**
  16527. * This array holds the node attributes of this builder
  16528. * created via {@link AttributeNode}.
  16529. *
  16530. * @type {Array<NodeAttribute>}
  16531. */
  16532. this.attributes = [];
  16533. /**
  16534. * This array holds the node attributes of this builder
  16535. * created via {@link BufferAttributeNode}.
  16536. *
  16537. * @type {Array<NodeAttribute>}
  16538. */
  16539. this.bufferAttributes = [];
  16540. /**
  16541. * This array holds the node varyings of this builder.
  16542. *
  16543. * @type {Array<NodeVarying>}
  16544. */
  16545. this.varyings = [];
  16546. /**
  16547. * This dictionary holds the (native) node codes of this builder.
  16548. * The codes are maintained in an array for each shader stage.
  16549. *
  16550. * @type {Object<String,Array<NodeCode>>}
  16551. */
  16552. this.codes = {};
  16553. /**
  16554. * This dictionary holds the node variables of this builder.
  16555. * The variables are maintained in an array for each shader stage.
  16556. *
  16557. * @type {Object<String,Array<NodeVar>>}
  16558. */
  16559. this.vars = {};
  16560. this.flow = { code: '' };
  16561. this.chaining = [];
  16562. this.stack = stack();
  16563. this.stacks = [];
  16564. this.tab = '\t';
  16565. this.currentFunctionNode = null;
  16566. this.context = {
  16567. material: this.material
  16568. };
  16569. this.cache = new NodeCache();
  16570. this.globalCache = this.cache;
  16571. this.flowsData = new WeakMap();
  16572. /**
  16573. * The current shader stage.
  16574. *
  16575. * @type {('vertex'|'fragment'|'compute')?}
  16576. */
  16577. this.shaderStage = null;
  16578. /**
  16579. * The current build stage.
  16580. *
  16581. * @type {('setup'|'analyze'|'generate')?}
  16582. */
  16583. this.buildStage = null;
  16584. this.useComparisonMethod = false;
  16585. }
  16586. /**
  16587. * Returns the bind groups of the current renderer.
  16588. *
  16589. * @return {ChainMap} The cache.
  16590. */
  16591. getBindGroupsCache() {
  16592. let bindGroupsCache = rendererCache.get( this.renderer );
  16593. if ( bindGroupsCache === undefined ) {
  16594. bindGroupsCache = new ChainMap();
  16595. rendererCache.set( this.renderer, bindGroupsCache );
  16596. }
  16597. return bindGroupsCache;
  16598. }
  16599. /**
  16600. * Factory method for creating an instance of {@link RenderTarget} with the given
  16601. * dimensions and options.
  16602. *
  16603. * @param {Number} width - The width of the render target.
  16604. * @param {Number} height - The height of the render target.
  16605. * @param {Object} options - The options of the render target.
  16606. * @return {RenderTarget} The render target.
  16607. */
  16608. createRenderTarget( width, height, options ) {
  16609. return new RenderTarget( width, height, options );
  16610. }
  16611. /**
  16612. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  16613. * dimensions and options.
  16614. *
  16615. * @param {Number} size - The size of the cube render target.
  16616. * @param {Object} options - The options of the cube render target.
  16617. * @return {CubeRenderTarget} The cube render target.
  16618. */
  16619. createCubeRenderTarget( size, options ) {
  16620. return new CubeRenderTarget( size, options );
  16621. }
  16622. /**
  16623. * Factory method for creating an instance of {@link PMREMGenerator}.
  16624. *
  16625. * @return {PMREMGenerator} The PMREM generator.
  16626. */
  16627. createPMREMGenerator() {
  16628. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  16629. return new PMREMGenerator( this.renderer );
  16630. }
  16631. /**
  16632. * Whether the given node is included in the internal array of nodes or not.
  16633. *
  16634. * @param {Node} node - The node to test.
  16635. * @return {Boolean} Whether the given node is included in the internal array of nodes or not.
  16636. */
  16637. includes( node ) {
  16638. return this.nodes.includes( node );
  16639. }
  16640. _getBindGroup( groupName, bindings ) {
  16641. const bindGroupsCache = this.getBindGroupsCache();
  16642. //
  16643. const bindingsArray = [];
  16644. let sharedGroup = true;
  16645. for ( const binding of bindings ) {
  16646. bindingsArray.push( binding );
  16647. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  16648. }
  16649. //
  16650. let bindGroup;
  16651. if ( sharedGroup ) {
  16652. bindGroup = bindGroupsCache.get( bindingsArray );
  16653. if ( bindGroup === undefined ) {
  16654. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  16655. bindGroupsCache.set( bindingsArray, bindGroup );
  16656. }
  16657. } else {
  16658. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  16659. }
  16660. return bindGroup;
  16661. }
  16662. getBindGroupArray( groupName, shaderStage ) {
  16663. const bindings = this.bindings[ shaderStage ];
  16664. let bindGroup = bindings[ groupName ];
  16665. if ( bindGroup === undefined ) {
  16666. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  16667. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  16668. }
  16669. bindings[ groupName ] = bindGroup = [];
  16670. }
  16671. return bindGroup;
  16672. }
  16673. getBindings() {
  16674. let bindingsGroups = this.bindGroups;
  16675. if ( bindingsGroups === null ) {
  16676. const groups = {};
  16677. const bindings = this.bindings;
  16678. for ( const shaderStage of shaderStages ) {
  16679. for ( const groupName in bindings[ shaderStage ] ) {
  16680. const uniforms = bindings[ shaderStage ][ groupName ];
  16681. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  16682. groupUniforms.push( ...uniforms );
  16683. }
  16684. }
  16685. bindingsGroups = [];
  16686. for ( const groupName in groups ) {
  16687. const group = groups[ groupName ];
  16688. const bindingsGroup = this._getBindGroup( groupName, group );
  16689. bindingsGroups.push( bindingsGroup );
  16690. }
  16691. this.bindGroups = bindingsGroups;
  16692. }
  16693. return bindingsGroups;
  16694. }
  16695. sortBindingGroups() {
  16696. const bindingsGroups = this.getBindings();
  16697. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  16698. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  16699. const bindingGroup = bindingsGroups[ i ];
  16700. this.bindingsIndexes[ bindingGroup.name ].group = i;
  16701. bindingGroup.index = i;
  16702. }
  16703. }
  16704. setHashNode( node, hash ) {
  16705. this.hashNodes[ hash ] = node;
  16706. }
  16707. addNode( node ) {
  16708. if ( this.nodes.includes( node ) === false ) {
  16709. this.nodes.push( node );
  16710. this.setHashNode( node, node.getHash( this ) );
  16711. }
  16712. }
  16713. addSequentialNode( node ) {
  16714. if ( this.sequentialNodes.includes( node ) === false ) {
  16715. this.sequentialNodes.push( node );
  16716. }
  16717. }
  16718. buildUpdateNodes() {
  16719. for ( const node of this.nodes ) {
  16720. const updateType = node.getUpdateType();
  16721. if ( updateType !== NodeUpdateType.NONE ) {
  16722. this.updateNodes.push( node.getSelf() );
  16723. }
  16724. }
  16725. for ( const node of this.sequentialNodes ) {
  16726. const updateBeforeType = node.getUpdateBeforeType();
  16727. const updateAfterType = node.getUpdateAfterType();
  16728. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  16729. this.updateBeforeNodes.push( node.getSelf() );
  16730. }
  16731. if ( updateAfterType !== NodeUpdateType.NONE ) {
  16732. this.updateAfterNodes.push( node.getSelf() );
  16733. }
  16734. }
  16735. }
  16736. get currentNode() {
  16737. return this.chaining[ this.chaining.length - 1 ];
  16738. }
  16739. isFilteredTexture( texture ) {
  16740. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  16741. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  16742. }
  16743. addChain( node ) {
  16744. /*
  16745. if ( this.chaining.indexOf( node ) !== - 1 ) {
  16746. console.warn( 'Recursive node: ', node );
  16747. }
  16748. */
  16749. this.chaining.push( node );
  16750. }
  16751. removeChain( node ) {
  16752. const lastChain = this.chaining.pop();
  16753. if ( lastChain !== node ) {
  16754. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  16755. }
  16756. }
  16757. getMethod( method ) {
  16758. return method;
  16759. }
  16760. getNodeFromHash( hash ) {
  16761. return this.hashNodes[ hash ];
  16762. }
  16763. addFlow( shaderStage, node ) {
  16764. this.flowNodes[ shaderStage ].push( node );
  16765. return node;
  16766. }
  16767. setContext( context ) {
  16768. this.context = context;
  16769. }
  16770. getContext() {
  16771. return this.context;
  16772. }
  16773. getSharedContext() {
  16774. ({ ...this.context });
  16775. return this.context;
  16776. }
  16777. setCache( cache ) {
  16778. this.cache = cache;
  16779. }
  16780. getCache() {
  16781. return this.cache;
  16782. }
  16783. getCacheFromNode( node, parent = true ) {
  16784. const data = this.getDataFromNode( node );
  16785. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  16786. return data.cache;
  16787. }
  16788. isAvailable( /*name*/ ) {
  16789. return false;
  16790. }
  16791. getVertexIndex() {
  16792. console.warn( 'Abstract function.' );
  16793. }
  16794. getInstanceIndex() {
  16795. console.warn( 'Abstract function.' );
  16796. }
  16797. getDrawIndex() {
  16798. console.warn( 'Abstract function.' );
  16799. }
  16800. getFrontFacing() {
  16801. console.warn( 'Abstract function.' );
  16802. }
  16803. getFragCoord() {
  16804. console.warn( 'Abstract function.' );
  16805. }
  16806. isFlipY() {
  16807. return false;
  16808. }
  16809. increaseUsage( node ) {
  16810. const nodeData = this.getDataFromNode( node );
  16811. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  16812. return nodeData.usageCount;
  16813. }
  16814. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  16815. console.warn( 'Abstract function.' );
  16816. }
  16817. generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  16818. console.warn( 'Abstract function.' );
  16819. }
  16820. generateConst( type, value = null ) {
  16821. if ( value === null ) {
  16822. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  16823. else if ( type === 'bool' ) value = false;
  16824. else if ( type === 'color' ) value = new Color();
  16825. else if ( type === 'vec2' ) value = new Vector2();
  16826. else if ( type === 'vec3' ) value = new Vector3();
  16827. else if ( type === 'vec4' ) value = new Vector4();
  16828. }
  16829. if ( type === 'float' ) return toFloat( value );
  16830. if ( type === 'int' ) return `${ Math.round( value ) }`;
  16831. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  16832. if ( type === 'bool' ) return value ? 'true' : 'false';
  16833. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  16834. const typeLength = this.getTypeLength( type );
  16835. const componentType = this.getComponentType( type );
  16836. const generateConst = value => this.generateConst( componentType, value );
  16837. if ( typeLength === 2 ) {
  16838. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  16839. } else if ( typeLength === 3 ) {
  16840. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  16841. } else if ( typeLength === 4 ) {
  16842. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  16843. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  16844. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  16845. } else if ( typeLength > 4 ) {
  16846. return `${ this.getType( type ) }()`;
  16847. }
  16848. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  16849. }
  16850. /**
  16851. * It might be necessary to convert certain data types to different ones
  16852. * so this method can be used to hide the conversion.
  16853. *
  16854. * @param {String} type - The type.
  16855. * @return {String} The updated type.
  16856. */
  16857. getType( type ) {
  16858. if ( type === 'color' ) return 'vec3';
  16859. return type;
  16860. }
  16861. /**
  16862. * Whether the given attribute name is defined in the geometry or not.
  16863. *
  16864. * @param {String} name - The attribute name.
  16865. * @return {Boolean} Whether the given attribute name is defined in the geometry.
  16866. */
  16867. hasGeometryAttribute( name ) {
  16868. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  16869. }
  16870. /**
  16871. * Returns a node attribute for the given name and type.
  16872. *
  16873. * @param {String} name - The attribute's name.
  16874. * @param {String} type - The attribute's type.
  16875. * @return {NodeAttribute} The node attribute.
  16876. */
  16877. getAttribute( name, type ) {
  16878. const attributes = this.attributes;
  16879. // find attribute
  16880. for ( const attribute of attributes ) {
  16881. if ( attribute.name === name ) {
  16882. return attribute;
  16883. }
  16884. }
  16885. // create a new if no exist
  16886. const attribute = new NodeAttribute( name, type );
  16887. attributes.push( attribute );
  16888. return attribute;
  16889. }
  16890. /**
  16891. * Returns for the given node and shader stage the property name for the shader.
  16892. *
  16893. * @param {Node} node - The node.
  16894. * @param {('vertex'|'fragment'|'compute')?} shaderStage - The current shader stage.
  16895. * @return {String} The property name.
  16896. */
  16897. getPropertyName( node/*, shaderStage*/ ) {
  16898. return node.name;
  16899. }
  16900. /**
  16901. * Whether the given type is a vector type or not.
  16902. *
  16903. * @param {String} type - The type to check.
  16904. * @return {Boolean} Whether the given type is a vector type or not.
  16905. */
  16906. isVector( type ) {
  16907. return /vec\d/.test( type );
  16908. }
  16909. /**
  16910. * Whether the given type is a matrix type or not.
  16911. *
  16912. * @param {String} type - The type to check.
  16913. * @return {Boolean} Whether the given type is a matrix type or not.
  16914. */
  16915. isMatrix( type ) {
  16916. return /mat\d/.test( type );
  16917. }
  16918. /**
  16919. * Whether the given type is a reference type or not.
  16920. *
  16921. * @param {String} type - The type to check.
  16922. * @return {Boolean} Whether the given type is a reference type or not.
  16923. */
  16924. isReference( type ) {
  16925. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  16926. }
  16927. /**
  16928. * Whether the given texture needs a conversion to working color space.
  16929. *
  16930. * @abstract
  16931. * @param {Texture} texture - The texture to check.
  16932. * @return {Boolean} Whether a color space conversion is required or not.
  16933. */
  16934. needsToWorkingColorSpace( /*texture*/ ) {
  16935. return false;
  16936. }
  16937. /**
  16938. * Returns the component type of a given texutre.
  16939. *
  16940. * @param {Texture} texture - The texture.
  16941. * @return {String} The component type.
  16942. */
  16943. getComponentTypeFromTexture( texture ) {
  16944. const type = texture.type;
  16945. if ( texture.isDataTexture ) {
  16946. if ( type === IntType ) return 'int';
  16947. if ( type === UnsignedIntType ) return 'uint';
  16948. }
  16949. return 'float';
  16950. }
  16951. /**
  16952. * Returns the element type for a given type.
  16953. *
  16954. * @param {String} type - The type.
  16955. * @return {String} The element type.
  16956. */
  16957. getElementType( type ) {
  16958. if ( type === 'mat2' ) return 'vec2';
  16959. if ( type === 'mat3' ) return 'vec3';
  16960. if ( type === 'mat4' ) return 'vec4';
  16961. return this.getComponentType( type );
  16962. }
  16963. /**
  16964. * Returns the component type for a given type.
  16965. *
  16966. * @param {String} type - The type.
  16967. * @return {String} The component type.
  16968. */
  16969. getComponentType( type ) {
  16970. type = this.getVectorType( type );
  16971. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  16972. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  16973. if ( componentType === null ) return null;
  16974. if ( componentType[ 1 ] === 'b' ) return 'bool';
  16975. if ( componentType[ 1 ] === 'i' ) return 'int';
  16976. if ( componentType[ 1 ] === 'u' ) return 'uint';
  16977. return 'float';
  16978. }
  16979. /**
  16980. * Returns the vector type for a given type.
  16981. *
  16982. * @param {String} type - The type.
  16983. * @return {String} The vector type.
  16984. */
  16985. getVectorType( type ) {
  16986. if ( type === 'color' ) return 'vec3';
  16987. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  16988. return type;
  16989. }
  16990. /**
  16991. * Returns the data type for the given the length and component type.
  16992. *
  16993. * @param {Number} length - The length.
  16994. * @param {String} [componentType='float'] - The component type.
  16995. * @return {String} The type.
  16996. */
  16997. getTypeFromLength( length, componentType = 'float' ) {
  16998. if ( length === 1 ) return componentType;
  16999. const baseType = getTypeFromLength( length );
  17000. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  17001. return prefix + baseType;
  17002. }
  17003. /**
  17004. * Returns the type for a given typed array.
  17005. *
  17006. * @param {TypedArray} type - The typed array.
  17007. * @return {String} The type.
  17008. */
  17009. getTypeFromArray( array ) {
  17010. return typeFromArray.get( array.constructor );
  17011. }
  17012. /**
  17013. * Returns the type for a given buffer attribute.
  17014. *
  17015. * @param {BufferAttribute} attribute - The buffer attribute.
  17016. * @return {String} The type.
  17017. */
  17018. getTypeFromAttribute( attribute ) {
  17019. let dataAttribute = attribute;
  17020. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  17021. const array = dataAttribute.array;
  17022. const itemSize = attribute.itemSize;
  17023. const normalized = attribute.normalized;
  17024. let arrayType;
  17025. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  17026. arrayType = this.getTypeFromArray( array );
  17027. }
  17028. return this.getTypeFromLength( itemSize, arrayType );
  17029. }
  17030. /**
  17031. * Returns the length for the given data type.
  17032. *
  17033. * @param {String} type - The data type.
  17034. * @return {Number} The length.
  17035. */
  17036. getTypeLength( type ) {
  17037. const vecType = this.getVectorType( type );
  17038. const vecNum = /vec([2-4])/.exec( vecType );
  17039. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  17040. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  17041. if ( /mat2/.test( type ) === true ) return 4;
  17042. if ( /mat3/.test( type ) === true ) return 9;
  17043. if ( /mat4/.test( type ) === true ) return 16;
  17044. return 0;
  17045. }
  17046. /**
  17047. * Returns the vector type for a given matrix type.
  17048. *
  17049. * @param {String} type - The matrix type.
  17050. * @return {String} The vector type.
  17051. */
  17052. getVectorFromMatrix( type ) {
  17053. return type.replace( 'mat', 'vec' );
  17054. }
  17055. /**
  17056. * For a given type this method changes the component type to the
  17057. * given value. E.g. `vec4` should be changed to the new component type
  17058. * `uint` which results in `uvec4`.
  17059. *
  17060. * @param {String} type - The type.
  17061. * @param {String} newComponentType - The new component type.
  17062. * @return {String} The new type.
  17063. */
  17064. changeComponentType( type, newComponentType ) {
  17065. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  17066. }
  17067. /**
  17068. * Returns the integer type pendant for the given type.
  17069. *
  17070. * @param {String} type - The type.
  17071. * @return {String} The integer type.
  17072. */
  17073. getIntegerType( type ) {
  17074. const componentType = this.getComponentType( type );
  17075. if ( componentType === 'int' || componentType === 'uint' ) return type;
  17076. return this.changeComponentType( type, 'int' );
  17077. }
  17078. addStack() {
  17079. this.stack = stack( this.stack );
  17080. this.stacks.push( getCurrentStack() || this.stack );
  17081. setCurrentStack( this.stack );
  17082. return this.stack;
  17083. }
  17084. removeStack() {
  17085. const lastStack = this.stack;
  17086. this.stack = lastStack.parent;
  17087. setCurrentStack( this.stacks.pop() );
  17088. return lastStack;
  17089. }
  17090. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  17091. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  17092. let nodeData = cache.getData( node );
  17093. if ( nodeData === undefined ) {
  17094. nodeData = {};
  17095. cache.setData( node, nodeData );
  17096. }
  17097. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  17098. return nodeData[ shaderStage ];
  17099. }
  17100. getNodeProperties( node, shaderStage = 'any' ) {
  17101. const nodeData = this.getDataFromNode( node, shaderStage );
  17102. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  17103. }
  17104. getBufferAttributeFromNode( node, type ) {
  17105. const nodeData = this.getDataFromNode( node );
  17106. let bufferAttribute = nodeData.bufferAttribute;
  17107. if ( bufferAttribute === undefined ) {
  17108. const index = this.uniforms.index ++;
  17109. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  17110. this.bufferAttributes.push( bufferAttribute );
  17111. nodeData.bufferAttribute = bufferAttribute;
  17112. }
  17113. return bufferAttribute;
  17114. }
  17115. getStructTypeFromNode( node, types, shaderStage = this.shaderStage ) {
  17116. const nodeData = this.getDataFromNode( node, shaderStage );
  17117. let structType = nodeData.structType;
  17118. if ( structType === undefined ) {
  17119. const index = this.structs.index ++;
  17120. structType = new StructTypeNode( 'StructType' + index, types );
  17121. this.structs[ shaderStage ].push( structType );
  17122. nodeData.structType = structType;
  17123. }
  17124. return structType;
  17125. }
  17126. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  17127. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  17128. let nodeUniform = nodeData.uniform;
  17129. if ( nodeUniform === undefined ) {
  17130. const index = this.uniforms.index ++;
  17131. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  17132. this.uniforms[ shaderStage ].push( nodeUniform );
  17133. nodeData.uniform = nodeUniform;
  17134. }
  17135. return nodeUniform;
  17136. }
  17137. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  17138. const nodeData = this.getDataFromNode( node, shaderStage );
  17139. let nodeVar = nodeData.variable;
  17140. if ( nodeVar === undefined ) {
  17141. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  17142. if ( name === null ) name = 'nodeVar' + vars.length;
  17143. nodeVar = new NodeVar( name, type );
  17144. vars.push( nodeVar );
  17145. nodeData.variable = nodeVar;
  17146. }
  17147. return nodeVar;
  17148. }
  17149. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  17150. const nodeData = this.getDataFromNode( node, 'any' );
  17151. let nodeVarying = nodeData.varying;
  17152. if ( nodeVarying === undefined ) {
  17153. const varyings = this.varyings;
  17154. const index = varyings.length;
  17155. if ( name === null ) name = 'nodeVarying' + index;
  17156. nodeVarying = new NodeVarying( name, type );
  17157. varyings.push( nodeVarying );
  17158. nodeData.varying = nodeVarying;
  17159. }
  17160. return nodeVarying;
  17161. }
  17162. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  17163. const nodeData = this.getDataFromNode( node );
  17164. let nodeCode = nodeData.code;
  17165. if ( nodeCode === undefined ) {
  17166. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  17167. const index = codes.length;
  17168. nodeCode = new NodeCode( 'nodeCode' + index, type );
  17169. codes.push( nodeCode );
  17170. nodeData.code = nodeCode;
  17171. }
  17172. return nodeCode;
  17173. }
  17174. addFlowCodeHierarchy( node, nodeBlock ) {
  17175. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  17176. let needsFlowCode = true;
  17177. let nodeBlockHierarchy = nodeBlock;
  17178. while ( nodeBlockHierarchy ) {
  17179. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  17180. needsFlowCode = false;
  17181. break;
  17182. }
  17183. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  17184. }
  17185. if ( needsFlowCode ) {
  17186. for ( const flowCode of flowCodes ) {
  17187. this.addLineFlowCode( flowCode );
  17188. }
  17189. }
  17190. }
  17191. addLineFlowCodeBlock( node, code, nodeBlock ) {
  17192. const nodeData = this.getDataFromNode( node );
  17193. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  17194. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  17195. flowCodes.push( code );
  17196. codeBlock.set( nodeBlock, true );
  17197. }
  17198. addLineFlowCode( code, node = null ) {
  17199. if ( code === '' ) return this;
  17200. if ( node !== null && this.context.nodeBlock ) {
  17201. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  17202. }
  17203. code = this.tab + code;
  17204. if ( ! /;\s*$/.test( code ) ) {
  17205. code = code + ';\n';
  17206. }
  17207. this.flow.code += code;
  17208. return this;
  17209. }
  17210. addFlowCode( code ) {
  17211. this.flow.code += code;
  17212. return this;
  17213. }
  17214. addFlowTab() {
  17215. this.tab += '\t';
  17216. return this;
  17217. }
  17218. removeFlowTab() {
  17219. this.tab = this.tab.slice( 0, - 1 );
  17220. return this;
  17221. }
  17222. getFlowData( node/*, shaderStage*/ ) {
  17223. return this.flowsData.get( node );
  17224. }
  17225. flowNode( node ) {
  17226. const output = node.getNodeType( this );
  17227. const flowData = this.flowChildNode( node, output );
  17228. this.flowsData.set( node, flowData );
  17229. return flowData;
  17230. }
  17231. buildFunctionNode( shaderNode ) {
  17232. const fn = new FunctionNode();
  17233. const previous = this.currentFunctionNode;
  17234. this.currentFunctionNode = fn;
  17235. fn.code = this.buildFunctionCode( shaderNode );
  17236. this.currentFunctionNode = previous;
  17237. return fn;
  17238. }
  17239. flowShaderNode( shaderNode ) {
  17240. const layout = shaderNode.layout;
  17241. const inputs = {
  17242. [ Symbol.iterator ]() {
  17243. let index = 0;
  17244. const values = Object.values( this );
  17245. return {
  17246. next: () => ( {
  17247. value: values[ index ],
  17248. done: index ++ >= values.length
  17249. } )
  17250. };
  17251. }
  17252. };
  17253. for ( const input of layout.inputs ) {
  17254. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  17255. }
  17256. //
  17257. shaderNode.layout = null;
  17258. const callNode = shaderNode.call( inputs );
  17259. const flowData = this.flowStagesNode( callNode, layout.type );
  17260. shaderNode.layout = layout;
  17261. return flowData;
  17262. }
  17263. flowStagesNode( node, output = null ) {
  17264. const previousFlow = this.flow;
  17265. const previousVars = this.vars;
  17266. const previousCache = this.cache;
  17267. const previousBuildStage = this.buildStage;
  17268. const previousStack = this.stack;
  17269. const flow = {
  17270. code: ''
  17271. };
  17272. this.flow = flow;
  17273. this.vars = {};
  17274. this.cache = new NodeCache();
  17275. this.stack = stack();
  17276. for ( const buildStage of defaultBuildStages ) {
  17277. this.setBuildStage( buildStage );
  17278. flow.result = node.build( this, output );
  17279. }
  17280. flow.vars = this.getVars( this.shaderStage );
  17281. this.flow = previousFlow;
  17282. this.vars = previousVars;
  17283. this.cache = previousCache;
  17284. this.stack = previousStack;
  17285. this.setBuildStage( previousBuildStage );
  17286. return flow;
  17287. }
  17288. getFunctionOperator() {
  17289. return null;
  17290. }
  17291. flowChildNode( node, output = null ) {
  17292. const previousFlow = this.flow;
  17293. const flow = {
  17294. code: ''
  17295. };
  17296. this.flow = flow;
  17297. flow.result = node.build( this, output );
  17298. this.flow = previousFlow;
  17299. return flow;
  17300. }
  17301. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  17302. const previousShaderStage = this.shaderStage;
  17303. this.setShaderStage( shaderStage );
  17304. const flowData = this.flowChildNode( node, output );
  17305. if ( propertyName !== null ) {
  17306. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  17307. }
  17308. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  17309. this.setShaderStage( previousShaderStage );
  17310. return flowData;
  17311. }
  17312. /**
  17313. * Returns an array holding all node attributes of this node builder.
  17314. *
  17315. * @return {Array<NodeAttribute>} The node attributes of this builder.
  17316. */
  17317. getAttributesArray() {
  17318. return this.attributes.concat( this.bufferAttributes );
  17319. }
  17320. /**
  17321. * Returns the attribute definitions as a shader string for the given shader stage.
  17322. *
  17323. * @abstract
  17324. * @param {('vertex'|'fragment'|'compute')?} shaderStage - The current shader stage.
  17325. * @return {String} The attribute code section.
  17326. */
  17327. getAttributes( /*shaderStage*/ ) {
  17328. console.warn( 'Abstract function.' );
  17329. }
  17330. /**
  17331. * Returns the varying definitions as a shader string for the given shader stage.
  17332. *
  17333. * @abstract
  17334. * @param {('vertex'|'fragment'|'compute')?} shaderStage - The current shader stage.
  17335. * @return {String} The varying code section.
  17336. */
  17337. getVaryings( /*shaderStage*/ ) {
  17338. console.warn( 'Abstract function.' );
  17339. }
  17340. /**
  17341. * Returns a single variable definition as a shader string for the given variable type and name.
  17342. *
  17343. * @param {String} type - The variable's type.
  17344. * @param {String} name - The variable's name.
  17345. * @return {String} The shader string.
  17346. */
  17347. getVar( type, name ) {
  17348. return `${ this.getType( type ) } ${ name }`;
  17349. }
  17350. /**
  17351. * Returns the variable definitions as a shader string for the given shader stage.
  17352. *
  17353. * @param {('vertex'|'fragment'|'compute')?} shaderStage - The current shader stage.
  17354. * @return {String} The variable code section.
  17355. */
  17356. getVars( shaderStage ) {
  17357. let snippet = '';
  17358. const vars = this.vars[ shaderStage ];
  17359. if ( vars !== undefined ) {
  17360. for ( const variable of vars ) {
  17361. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  17362. }
  17363. }
  17364. return snippet;
  17365. }
  17366. /**
  17367. * Returns the uniform definitions as a shader string for the given shader stage.
  17368. *
  17369. * @abstract
  17370. * @param {('vertex'|'fragment'|'compute')?} shaderStage - The current shader stage.
  17371. * @return {String} The uniform code section.
  17372. */
  17373. getUniforms( /*shaderStage*/ ) {
  17374. console.warn( 'Abstract function.' );
  17375. }
  17376. /**
  17377. * Returns the native code definitions as a shader string for the given shader stage.
  17378. *
  17379. * @param {('vertex'|'fragment'|'compute')?} shaderStage - The current shader stage.
  17380. * @return {String} The native code section.
  17381. */
  17382. getCodes( shaderStage ) {
  17383. const codes = this.codes[ shaderStage ];
  17384. let code = '';
  17385. if ( codes !== undefined ) {
  17386. for ( const nodeCode of codes ) {
  17387. code += nodeCode.code + '\n';
  17388. }
  17389. }
  17390. return code;
  17391. }
  17392. getHash() {
  17393. return this.vertexShader + this.fragmentShader + this.computeShader;
  17394. }
  17395. /**
  17396. * Sets the current shader stage.
  17397. *
  17398. * @param {('vertex'|'fragment'|'compute')?} shaderStage - The shader stage to set.
  17399. */
  17400. setShaderStage( shaderStage ) {
  17401. this.shaderStage = shaderStage;
  17402. }
  17403. /**
  17404. * Returns the current shader stage.
  17405. *
  17406. * @return {('vertex'|'fragment'|'compute')?} The current shader stage.
  17407. */
  17408. getShaderStage() {
  17409. return this.shaderStage;
  17410. }
  17411. /**
  17412. * Sets the current build stage.
  17413. *
  17414. * @param {('setup'|'analyze'|'generate')?} buildStage - The build stage to set.
  17415. */
  17416. setBuildStage( buildStage ) {
  17417. this.buildStage = buildStage;
  17418. }
  17419. /**
  17420. * Returns the current build stage.
  17421. *
  17422. * @return {('setup'|'analyze'|'generate')?} The current build stage.
  17423. */
  17424. getBuildStage() {
  17425. return this.buildStage;
  17426. }
  17427. /**
  17428. * Controls the code build of the shader stages.
  17429. *
  17430. * @abstract
  17431. */
  17432. buildCode() {
  17433. console.warn( 'Abstract function.' );
  17434. }
  17435. /**
  17436. * Central build method which controls the build for the given object.
  17437. *
  17438. * @return {NodeBuilder} A reference to this node builder.
  17439. */
  17440. build() {
  17441. const { object, material, renderer } = this;
  17442. if ( material !== null ) {
  17443. let nodeMaterial = renderer.library.fromMaterial( material );
  17444. if ( nodeMaterial === null ) {
  17445. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  17446. nodeMaterial = new NodeMaterial();
  17447. }
  17448. nodeMaterial.build( this );
  17449. } else {
  17450. this.addFlow( 'compute', object );
  17451. }
  17452. // setup() -> stage 1: create possible new nodes and returns an output reference node
  17453. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  17454. // generate() -> stage 3: generate shader
  17455. for ( const buildStage of defaultBuildStages ) {
  17456. this.setBuildStage( buildStage );
  17457. if ( this.context.vertex && this.context.vertex.isNode ) {
  17458. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  17459. }
  17460. for ( const shaderStage of shaderStages ) {
  17461. this.setShaderStage( shaderStage );
  17462. const flowNodes = this.flowNodes[ shaderStage ];
  17463. for ( const node of flowNodes ) {
  17464. if ( buildStage === 'generate' ) {
  17465. this.flowNode( node );
  17466. } else {
  17467. node.build( this );
  17468. }
  17469. }
  17470. }
  17471. }
  17472. this.setBuildStage( null );
  17473. this.setShaderStage( null );
  17474. // stage 4: build code for a specific output
  17475. this.buildCode();
  17476. this.buildUpdateNodes();
  17477. return this;
  17478. }
  17479. getNodeUniform( uniformNode, type ) {
  17480. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  17481. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  17482. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  17483. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  17484. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  17485. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  17486. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  17487. throw new Error( `Uniform "${type}" not declared.` );
  17488. }
  17489. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  17490. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  17491. }
  17492. format( snippet, fromType, toType ) {
  17493. fromType = this.getVectorType( fromType );
  17494. toType = this.getVectorType( toType );
  17495. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  17496. return snippet;
  17497. }
  17498. const fromTypeLength = this.getTypeLength( fromType );
  17499. const toTypeLength = this.getTypeLength( toType );
  17500. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  17501. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  17502. }
  17503. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  17504. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  17505. }
  17506. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  17507. // @TODO: ignore for now
  17508. return snippet;
  17509. }
  17510. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  17511. // @TODO: ignore for now
  17512. return snippet;
  17513. }
  17514. if ( fromTypeLength === toTypeLength ) {
  17515. return `${ this.getType( toType ) }( ${ snippet } )`;
  17516. }
  17517. if ( fromTypeLength > toTypeLength ) {
  17518. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  17519. }
  17520. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  17521. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  17522. }
  17523. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  17524. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  17525. }
  17526. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  17527. // convert a number value to vector type, e.g:
  17528. // vec3( 1u ) -> vec3( float( 1u ) )
  17529. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  17530. }
  17531. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  17532. }
  17533. /**
  17534. * Returns a signature with the engine's current revision.
  17535. *
  17536. * @return {String} The signature.
  17537. */
  17538. getSignature() {
  17539. return `// Three.js r${ REVISION } - Node System\n`;
  17540. }
  17541. }
  17542. /**
  17543. * Management class for updating nodes. The module tracks metrics like
  17544. * the elapsed time, delta time, the render and frame ID to correctly
  17545. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  17546. * and {@link Node#updateAfter} depending on the node's configuration.
  17547. */
  17548. class NodeFrame {
  17549. /**
  17550. * Constructs a new node fame.
  17551. */
  17552. constructor() {
  17553. /**
  17554. * The elapsed time in seconds.
  17555. *
  17556. * @type {Number}
  17557. * @default 0
  17558. */
  17559. this.time = 0;
  17560. /**
  17561. * The delta time in seconds.
  17562. *
  17563. * @type {Number}
  17564. * @default 0
  17565. */
  17566. this.deltaTime = 0;
  17567. /**
  17568. * The frame ID.
  17569. *
  17570. * @type {Number}
  17571. * @default 0
  17572. */
  17573. this.frameId = 0;
  17574. /**
  17575. * The render ID.
  17576. *
  17577. * @type {Number}
  17578. * @default 0
  17579. */
  17580. this.renderId = 0;
  17581. /**
  17582. * Used to control the {@link Node#update} call.
  17583. *
  17584. * @type {WeakMap}
  17585. */
  17586. this.updateMap = new WeakMap();
  17587. /**
  17588. * Used to control the {@link Node#updateBefore} call.
  17589. *
  17590. * @type {WeakMap}
  17591. */
  17592. this.updateBeforeMap = new WeakMap();
  17593. /**
  17594. * Used to control the {@link Node#updateAfter} call.
  17595. *
  17596. * @type {WeakMap}
  17597. */
  17598. this.updateAfterMap = new WeakMap();
  17599. /**
  17600. * A reference to the current renderer.
  17601. *
  17602. * @type {Renderer?}
  17603. * @default null
  17604. */
  17605. this.renderer = null;
  17606. /**
  17607. * A reference to the current material.
  17608. *
  17609. * @type {Material?}
  17610. * @default null
  17611. */
  17612. this.material = null;
  17613. /**
  17614. * A reference to the current camera.
  17615. *
  17616. * @type {Camera?}
  17617. * @default null
  17618. */
  17619. this.camera = null;
  17620. /**
  17621. * A reference to the current 3D object.
  17622. *
  17623. * @type {Object3D?}
  17624. * @default null
  17625. */
  17626. this.object = null;
  17627. /**
  17628. * A reference to the current scene.
  17629. *
  17630. * @type {Scene?}
  17631. * @default null
  17632. */
  17633. this.scene = null;
  17634. }
  17635. /**
  17636. * Returns a dictionary for a given node and update map which
  17637. * is used to correctly call node update methods per frame or render.
  17638. *
  17639. * @private
  17640. * @param {WeakMap} referenceMap - The reference weak map.
  17641. * @param {Node} nodeRef - The reference to the current node.
  17642. * @return {Object<String,WeakMap>} The dictionary.
  17643. */
  17644. _getMaps( referenceMap, nodeRef ) {
  17645. let maps = referenceMap.get( nodeRef );
  17646. if ( maps === undefined ) {
  17647. maps = {
  17648. renderMap: new WeakMap(),
  17649. frameMap: new WeakMap()
  17650. };
  17651. referenceMap.set( nodeRef, maps );
  17652. }
  17653. return maps;
  17654. }
  17655. /**
  17656. * This method executes the {@link Node#updateBefore} for the given node.
  17657. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  17658. * is only executed once per frame, render or object depending on the update
  17659. * type.
  17660. *
  17661. * @param {Node} node - The node that should be updated.
  17662. */
  17663. updateBeforeNode( node ) {
  17664. const updateType = node.getUpdateBeforeType();
  17665. const reference = node.updateReference( this );
  17666. if ( updateType === NodeUpdateType.FRAME ) {
  17667. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  17668. if ( frameMap.get( reference ) !== this.frameId ) {
  17669. if ( node.updateBefore( this ) !== false ) {
  17670. frameMap.set( reference, this.frameId );
  17671. }
  17672. }
  17673. } else if ( updateType === NodeUpdateType.RENDER ) {
  17674. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  17675. if ( renderMap.get( reference ) !== this.renderId ) {
  17676. if ( node.updateBefore( this ) !== false ) {
  17677. renderMap.set( reference, this.renderId );
  17678. }
  17679. }
  17680. } else if ( updateType === NodeUpdateType.OBJECT ) {
  17681. node.updateBefore( this );
  17682. }
  17683. }
  17684. /**
  17685. * This method executes the {@link Node#updateAfter} for the given node.
  17686. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  17687. * is only executed once per frame, render or object depending on the update
  17688. * type.
  17689. *
  17690. * @param {Node} node - The node that should be updated.
  17691. */
  17692. updateAfterNode( node ) {
  17693. const updateType = node.getUpdateAfterType();
  17694. const reference = node.updateReference( this );
  17695. if ( updateType === NodeUpdateType.FRAME ) {
  17696. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  17697. if ( frameMap.get( reference ) !== this.frameId ) {
  17698. if ( node.updateAfter( this ) !== false ) {
  17699. frameMap.set( reference, this.frameId );
  17700. }
  17701. }
  17702. } else if ( updateType === NodeUpdateType.RENDER ) {
  17703. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  17704. if ( renderMap.get( reference ) !== this.renderId ) {
  17705. if ( node.updateAfter( this ) !== false ) {
  17706. renderMap.set( reference, this.renderId );
  17707. }
  17708. }
  17709. } else if ( updateType === NodeUpdateType.OBJECT ) {
  17710. node.updateAfter( this );
  17711. }
  17712. }
  17713. /**
  17714. * This method executes the {@link Node#update} for the given node.
  17715. * It makes sure {@link Node#updateType} is honored meaning the update
  17716. * is only executed once per frame, render or object depending on the update
  17717. * type.
  17718. *
  17719. * @param {Node} node - The node that should be updated.
  17720. */
  17721. updateNode( node ) {
  17722. const updateType = node.getUpdateType();
  17723. const reference = node.updateReference( this );
  17724. if ( updateType === NodeUpdateType.FRAME ) {
  17725. const { frameMap } = this._getMaps( this.updateMap, reference );
  17726. if ( frameMap.get( reference ) !== this.frameId ) {
  17727. if ( node.update( this ) !== false ) {
  17728. frameMap.set( reference, this.frameId );
  17729. }
  17730. }
  17731. } else if ( updateType === NodeUpdateType.RENDER ) {
  17732. const { renderMap } = this._getMaps( this.updateMap, reference );
  17733. if ( renderMap.get( reference ) !== this.renderId ) {
  17734. if ( node.update( this ) !== false ) {
  17735. renderMap.set( reference, this.renderId );
  17736. }
  17737. }
  17738. } else if ( updateType === NodeUpdateType.OBJECT ) {
  17739. node.update( this );
  17740. }
  17741. }
  17742. /**
  17743. * Updates the internal state of the node frame. This method is
  17744. * called by the renderer in its internal animation loop.
  17745. */
  17746. update() {
  17747. this.frameId ++;
  17748. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  17749. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  17750. this.lastTime = performance.now();
  17751. this.time += this.deltaTime;
  17752. }
  17753. }
  17754. /**
  17755. * Describes the input of a {@link NodeFunction}.
  17756. */
  17757. class NodeFunctionInput {
  17758. /**
  17759. * Constructs a new node function input.
  17760. *
  17761. * @param {String} type - The input type.
  17762. * @param {String} name - The input name.
  17763. * @param {Number?} [count=null] - TODO (only relevant for GLSL).
  17764. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  17765. * @param {Boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  17766. */
  17767. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  17768. /**
  17769. * The input type.
  17770. *
  17771. * @type {String}
  17772. */
  17773. this.type = type;
  17774. /**
  17775. * The input name.
  17776. *
  17777. * @type {String}
  17778. */
  17779. this.name = name;
  17780. /**
  17781. * TODO (only relevant for GLSL).
  17782. *
  17783. * @type {Number?}
  17784. * @default null
  17785. */
  17786. this.count = count;
  17787. /**
  17788. *The parameter qualifier (only relevant for GLSL).
  17789. *
  17790. * @type {('in'|'out'|'inout')}
  17791. * @default ''
  17792. */
  17793. this.qualifier = qualifier;
  17794. /**
  17795. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  17796. *
  17797. * @type {Boolean}
  17798. * @default false
  17799. */
  17800. this.isConst = isConst;
  17801. }
  17802. }
  17803. NodeFunctionInput.isNodeFunctionInput = true;
  17804. class DirectionalLightNode extends AnalyticLightNode {
  17805. static get type() {
  17806. return 'DirectionalLightNode';
  17807. }
  17808. constructor( light = null ) {
  17809. super( light );
  17810. }
  17811. setup( builder ) {
  17812. super.setup( builder );
  17813. const lightingModel = builder.context.lightingModel;
  17814. const lightColor = this.colorNode;
  17815. const lightDirection = lightTargetDirection( this.light );
  17816. const reflectedLight = builder.context.reflectedLight;
  17817. lightingModel.direct( {
  17818. lightDirection,
  17819. lightColor,
  17820. reflectedLight
  17821. }, builder.stack, builder );
  17822. }
  17823. }
  17824. const _matrix41 = /*@__PURE__*/ new Matrix4();
  17825. const _matrix42 = /*@__PURE__*/ new Matrix4();
  17826. let ltcLib = null;
  17827. class RectAreaLightNode extends AnalyticLightNode {
  17828. static get type() {
  17829. return 'RectAreaLightNode';
  17830. }
  17831. constructor( light = null ) {
  17832. super( light );
  17833. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  17834. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  17835. this.updateType = NodeUpdateType.RENDER;
  17836. }
  17837. update( frame ) {
  17838. super.update( frame );
  17839. const { light } = this;
  17840. const viewMatrix = frame.camera.matrixWorldInverse;
  17841. _matrix42.identity();
  17842. _matrix41.copy( light.matrixWorld );
  17843. _matrix41.premultiply( viewMatrix );
  17844. _matrix42.extractRotation( _matrix41 );
  17845. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  17846. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  17847. this.halfWidth.value.applyMatrix4( _matrix42 );
  17848. this.halfHeight.value.applyMatrix4( _matrix42 );
  17849. }
  17850. setup( builder ) {
  17851. super.setup( builder );
  17852. let ltc_1, ltc_2;
  17853. if ( builder.isAvailable( 'float32Filterable' ) ) {
  17854. ltc_1 = texture( ltcLib.LTC_FLOAT_1 );
  17855. ltc_2 = texture( ltcLib.LTC_FLOAT_2 );
  17856. } else {
  17857. ltc_1 = texture( ltcLib.LTC_HALF_1 );
  17858. ltc_2 = texture( ltcLib.LTC_HALF_2 );
  17859. }
  17860. const { colorNode, light } = this;
  17861. const lightingModel = builder.context.lightingModel;
  17862. const lightPosition = lightViewPosition( light );
  17863. const reflectedLight = builder.context.reflectedLight;
  17864. lightingModel.directRectArea( {
  17865. lightColor: colorNode,
  17866. lightPosition,
  17867. halfWidth: this.halfWidth,
  17868. halfHeight: this.halfHeight,
  17869. reflectedLight,
  17870. ltc_1,
  17871. ltc_2
  17872. }, builder.stack, builder );
  17873. }
  17874. static setLTC( ltc ) {
  17875. ltcLib = ltc;
  17876. }
  17877. }
  17878. class SpotLightNode extends AnalyticLightNode {
  17879. static get type() {
  17880. return 'SpotLightNode';
  17881. }
  17882. constructor( light = null ) {
  17883. super( light );
  17884. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  17885. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  17886. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  17887. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  17888. }
  17889. update( frame ) {
  17890. super.update( frame );
  17891. const { light } = this;
  17892. this.coneCosNode.value = Math.cos( light.angle );
  17893. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  17894. this.cutoffDistanceNode.value = light.distance;
  17895. this.decayExponentNode.value = light.decay;
  17896. }
  17897. getSpotAttenuation( angleCosine ) {
  17898. const { coneCosNode, penumbraCosNode } = this;
  17899. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  17900. }
  17901. setup( builder ) {
  17902. super.setup( builder );
  17903. const lightingModel = builder.context.lightingModel;
  17904. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  17905. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  17906. const lightDirection = lVector.normalize();
  17907. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  17908. const spotAttenuation = this.getSpotAttenuation( angleCos );
  17909. const lightDistance = lVector.length();
  17910. const lightAttenuation = getDistanceAttenuation( {
  17911. lightDistance,
  17912. cutoffDistance: cutoffDistanceNode,
  17913. decayExponent: decayExponentNode
  17914. } );
  17915. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  17916. if ( light.map ) {
  17917. const spotLightCoord = lightProjectionUV( light );
  17918. const projectedTexture = texture( light.map, spotLightCoord.xy ).onRenderUpdate( () => light.map );
  17919. const inSpotLightMap = spotLightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  17920. lightColor = inSpotLightMap.select( lightColor.mul( projectedTexture ), lightColor );
  17921. }
  17922. const reflectedLight = builder.context.reflectedLight;
  17923. lightingModel.direct( {
  17924. lightDirection,
  17925. lightColor,
  17926. reflectedLight
  17927. }, builder.stack, builder );
  17928. }
  17929. }
  17930. class IESSpotLightNode extends SpotLightNode {
  17931. static get type() {
  17932. return 'IESSpotLightNode';
  17933. }
  17934. getSpotAttenuation( angleCosine ) {
  17935. const iesMap = this.light.iesMap;
  17936. let spotAttenuation = null;
  17937. if ( iesMap && iesMap.isTexture === true ) {
  17938. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  17939. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  17940. } else {
  17941. spotAttenuation = super.getSpotAttenuation( angleCosine );
  17942. }
  17943. return spotAttenuation;
  17944. }
  17945. }
  17946. class AmbientLightNode extends AnalyticLightNode {
  17947. static get type() {
  17948. return 'AmbientLightNode';
  17949. }
  17950. constructor( light = null ) {
  17951. super( light );
  17952. }
  17953. setup( { context } ) {
  17954. context.irradiance.addAssign( this.colorNode );
  17955. }
  17956. }
  17957. class HemisphereLightNode extends AnalyticLightNode {
  17958. static get type() {
  17959. return 'HemisphereLightNode';
  17960. }
  17961. constructor( light = null ) {
  17962. super( light );
  17963. this.lightPositionNode = lightPosition( light );
  17964. this.lightDirectionNode = this.lightPositionNode.normalize();
  17965. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  17966. }
  17967. update( frame ) {
  17968. const { light } = this;
  17969. super.update( frame );
  17970. this.lightPositionNode.object3d = light;
  17971. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  17972. }
  17973. setup( builder ) {
  17974. const { colorNode, groundColorNode, lightDirectionNode } = this;
  17975. const dotNL = normalView.dot( lightDirectionNode );
  17976. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  17977. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  17978. builder.context.irradiance.addAssign( irradiance );
  17979. }
  17980. }
  17981. class LightProbeNode extends AnalyticLightNode {
  17982. static get type() {
  17983. return 'LightProbeNode';
  17984. }
  17985. constructor( light = null ) {
  17986. super( light );
  17987. const array = [];
  17988. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  17989. this.lightProbe = uniformArray( array );
  17990. }
  17991. update( frame ) {
  17992. const { light } = this;
  17993. super.update( frame );
  17994. //
  17995. for ( let i = 0; i < 9; i ++ ) {
  17996. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  17997. }
  17998. }
  17999. setup( builder ) {
  18000. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  18001. builder.context.irradiance.addAssign( irradiance );
  18002. }
  18003. }
  18004. /**
  18005. * Base class for node parsers. A derived parser must be implemented
  18006. * for each supported native shader language.
  18007. */
  18008. class NodeParser {
  18009. /**
  18010. * The method parses the given native code an returns a node function.
  18011. *
  18012. * @abstract
  18013. * @param {String} source - The native shader code.
  18014. * @return {NodeFunction} A node function.
  18015. */
  18016. parseFunction( /*source*/ ) {
  18017. console.warn( 'Abstract function.' );
  18018. }
  18019. }
  18020. /**
  18021. * Base class for node functions. A derived module must be implemented
  18022. * for each supported native shader language. Similar to other `Node*` modules,
  18023. * this class is only relevant during the building process and not used
  18024. * in user-level code.
  18025. */
  18026. class NodeFunction {
  18027. /**
  18028. * Constructs a new node function.
  18029. *
  18030. * @param {String} type - The node type. This type is the return type of the node function.
  18031. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  18032. * @param {String} [name=''] - The function's name.
  18033. * @param {String} [precision=''] - The precision qualifier.
  18034. */
  18035. constructor( type, inputs, name = '', precision = '' ) {
  18036. /**
  18037. * The node type. This type is the return type of the node function.
  18038. *
  18039. * @type {String}
  18040. */
  18041. this.type = type;
  18042. /**
  18043. * The function's inputs.
  18044. *
  18045. * @type {Array<NodeFunctionInput>}
  18046. */
  18047. this.inputs = inputs;
  18048. /**
  18049. * The name of the uniform.
  18050. *
  18051. * @type {String}
  18052. * @default ''
  18053. */
  18054. this.name = name;
  18055. /**
  18056. * The precision qualifier.
  18057. *
  18058. * @type {String}
  18059. * @default ''
  18060. */
  18061. this.precision = precision;
  18062. }
  18063. /**
  18064. * This method returns the native code of the node function.
  18065. *
  18066. * @abstract
  18067. * @param {String} name - The function's name.
  18068. * @return {String} A shader code.
  18069. */
  18070. getCode( /*name = this.name*/ ) {
  18071. console.warn( 'Abstract function.' );
  18072. }
  18073. }
  18074. NodeFunction.isNodeFunction = true;
  18075. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  18076. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  18077. const pragmaMain = '#pragma main';
  18078. const parse$1 = ( source ) => {
  18079. source = source.trim();
  18080. const pragmaMainIndex = source.indexOf( pragmaMain );
  18081. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  18082. const declaration = mainCode.match( declarationRegexp$1 );
  18083. if ( declaration !== null && declaration.length === 5 ) {
  18084. // tokenizer
  18085. const inputsCode = declaration[ 4 ];
  18086. const propsMatches = [];
  18087. let nameMatch = null;
  18088. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  18089. propsMatches.push( nameMatch );
  18090. }
  18091. // parser
  18092. const inputs = [];
  18093. let i = 0;
  18094. while ( i < propsMatches.length ) {
  18095. const isConst = propsMatches[ i ][ 0 ] === 'const';
  18096. if ( isConst === true ) {
  18097. i ++;
  18098. }
  18099. let qualifier = propsMatches[ i ][ 0 ];
  18100. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  18101. i ++;
  18102. } else {
  18103. qualifier = '';
  18104. }
  18105. const type = propsMatches[ i ++ ][ 0 ];
  18106. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  18107. if ( Number.isNaN( count ) === false ) i ++;
  18108. else count = null;
  18109. const name = propsMatches[ i ++ ][ 0 ];
  18110. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  18111. }
  18112. //
  18113. const blockCode = mainCode.substring( declaration[ 0 ].length );
  18114. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  18115. const type = declaration[ 2 ];
  18116. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  18117. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  18118. return {
  18119. type,
  18120. inputs,
  18121. name,
  18122. precision,
  18123. inputsCode,
  18124. blockCode,
  18125. headerCode
  18126. };
  18127. } else {
  18128. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  18129. }
  18130. };
  18131. /**
  18132. * This class represents a GLSL node function.
  18133. *
  18134. * @augments NodeFunction
  18135. */
  18136. class GLSLNodeFunction extends NodeFunction {
  18137. /**
  18138. * Constructs a new GLSL node function.
  18139. *
  18140. * @param {String} source - The GLSL source.
  18141. */
  18142. constructor( source ) {
  18143. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  18144. super( type, inputs, name, precision );
  18145. this.inputsCode = inputsCode;
  18146. this.blockCode = blockCode;
  18147. this.headerCode = headerCode;
  18148. }
  18149. /**
  18150. * This method returns the GLSL code of the node function.
  18151. *
  18152. * @param {String} [name=this.name] - The function's name.
  18153. * @return {String} The shader code.
  18154. */
  18155. getCode( name = this.name ) {
  18156. let code;
  18157. const blockCode = this.blockCode;
  18158. if ( blockCode !== '' ) {
  18159. const { type, inputsCode, headerCode, precision } = this;
  18160. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  18161. if ( precision !== '' ) {
  18162. declarationCode = `${ precision } ${ declarationCode }`;
  18163. }
  18164. code = headerCode + declarationCode + blockCode;
  18165. } else {
  18166. // interface function
  18167. code = '';
  18168. }
  18169. return code;
  18170. }
  18171. }
  18172. /**
  18173. * A GLSL node parser.
  18174. *
  18175. * @augments NodeParser
  18176. */
  18177. class GLSLNodeParser extends NodeParser {
  18178. /**
  18179. * The method parses the given GLSL code an returns a node function.
  18180. *
  18181. * @param {String} source - The GLSL code.
  18182. * @return {GLSLNodeFunction} A node function.
  18183. */
  18184. parseFunction( source ) {
  18185. return new GLSLNodeFunction( source );
  18186. }
  18187. }
  18188. const outputNodeMap = new WeakMap();
  18189. class Nodes extends DataMap {
  18190. constructor( renderer, backend ) {
  18191. super();
  18192. this.renderer = renderer;
  18193. this.backend = backend;
  18194. this.nodeFrame = new NodeFrame();
  18195. this.nodeBuilderCache = new Map();
  18196. this.callHashCache = new ChainMap();
  18197. this.groupsData = new ChainMap();
  18198. }
  18199. updateGroup( nodeUniformsGroup ) {
  18200. const groupNode = nodeUniformsGroup.groupNode;
  18201. const name = groupNode.name;
  18202. // objectGroup is every updated
  18203. if ( name === objectGroup.name ) return true;
  18204. // renderGroup is updated once per render/compute call
  18205. if ( name === renderGroup.name ) {
  18206. const uniformsGroupData = this.get( nodeUniformsGroup );
  18207. const renderId = this.nodeFrame.renderId;
  18208. if ( uniformsGroupData.renderId !== renderId ) {
  18209. uniformsGroupData.renderId = renderId;
  18210. return true;
  18211. }
  18212. return false;
  18213. }
  18214. // frameGroup is updated once per frame
  18215. if ( name === frameGroup.name ) {
  18216. const uniformsGroupData = this.get( nodeUniformsGroup );
  18217. const frameId = this.nodeFrame.frameId;
  18218. if ( uniformsGroupData.frameId !== frameId ) {
  18219. uniformsGroupData.frameId = frameId;
  18220. return true;
  18221. }
  18222. return false;
  18223. }
  18224. // other groups are updated just when groupNode.needsUpdate is true
  18225. const groupChain = [ groupNode, nodeUniformsGroup ];
  18226. let groupData = this.groupsData.get( groupChain );
  18227. if ( groupData === undefined ) this.groupsData.set( groupChain, groupData = {} );
  18228. if ( groupData.version !== groupNode.version ) {
  18229. groupData.version = groupNode.version;
  18230. return true;
  18231. }
  18232. return false;
  18233. }
  18234. getForRenderCacheKey( renderObject ) {
  18235. return renderObject.initialCacheKey;
  18236. }
  18237. getForRender( renderObject ) {
  18238. const renderObjectData = this.get( renderObject );
  18239. let nodeBuilderState = renderObjectData.nodeBuilderState;
  18240. if ( nodeBuilderState === undefined ) {
  18241. const { nodeBuilderCache } = this;
  18242. const cacheKey = this.getForRenderCacheKey( renderObject );
  18243. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  18244. if ( nodeBuilderState === undefined ) {
  18245. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  18246. nodeBuilder.scene = renderObject.scene;
  18247. nodeBuilder.material = renderObject.material;
  18248. nodeBuilder.camera = renderObject.camera;
  18249. nodeBuilder.context.material = renderObject.material;
  18250. nodeBuilder.lightsNode = renderObject.lightsNode;
  18251. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  18252. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  18253. nodeBuilder.clippingContext = renderObject.clippingContext;
  18254. nodeBuilder.build();
  18255. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  18256. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  18257. }
  18258. nodeBuilderState.usedTimes ++;
  18259. renderObjectData.nodeBuilderState = nodeBuilderState;
  18260. }
  18261. return nodeBuilderState;
  18262. }
  18263. delete( object ) {
  18264. if ( object.isRenderObject ) {
  18265. const nodeBuilderState = this.get( object ).nodeBuilderState;
  18266. nodeBuilderState.usedTimes --;
  18267. if ( nodeBuilderState.usedTimes === 0 ) {
  18268. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  18269. }
  18270. }
  18271. return super.delete( object );
  18272. }
  18273. getForCompute( computeNode ) {
  18274. const computeData = this.get( computeNode );
  18275. let nodeBuilderState = computeData.nodeBuilderState;
  18276. if ( nodeBuilderState === undefined ) {
  18277. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  18278. nodeBuilder.build();
  18279. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  18280. computeData.nodeBuilderState = nodeBuilderState;
  18281. }
  18282. return nodeBuilderState;
  18283. }
  18284. _createNodeBuilderState( nodeBuilder ) {
  18285. return new NodeBuilderState(
  18286. nodeBuilder.vertexShader,
  18287. nodeBuilder.fragmentShader,
  18288. nodeBuilder.computeShader,
  18289. nodeBuilder.getAttributesArray(),
  18290. nodeBuilder.getBindings(),
  18291. nodeBuilder.updateNodes,
  18292. nodeBuilder.updateBeforeNodes,
  18293. nodeBuilder.updateAfterNodes,
  18294. nodeBuilder.monitor,
  18295. nodeBuilder.transforms
  18296. );
  18297. }
  18298. getEnvironmentNode( scene ) {
  18299. return scene.environmentNode || this.get( scene ).environmentNode || null;
  18300. }
  18301. getBackgroundNode( scene ) {
  18302. return scene.backgroundNode || this.get( scene ).backgroundNode || null;
  18303. }
  18304. getFogNode( scene ) {
  18305. return scene.fogNode || this.get( scene ).fogNode || null;
  18306. }
  18307. getCacheKey( scene, lightsNode ) {
  18308. const chain = [ scene, lightsNode ];
  18309. const callId = this.renderer.info.calls;
  18310. let cacheKeyData = this.callHashCache.get( chain );
  18311. if ( cacheKeyData === undefined || cacheKeyData.callId !== callId ) {
  18312. const environmentNode = this.getEnvironmentNode( scene );
  18313. const fogNode = this.getFogNode( scene );
  18314. const values = [];
  18315. if ( lightsNode ) values.push( lightsNode.getCacheKey( true ) );
  18316. if ( environmentNode ) values.push( environmentNode.getCacheKey() );
  18317. if ( fogNode ) values.push( fogNode.getCacheKey() );
  18318. values.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  18319. cacheKeyData = {
  18320. callId,
  18321. cacheKey: hashArray( values )
  18322. };
  18323. this.callHashCache.set( chain, cacheKeyData );
  18324. }
  18325. return cacheKeyData.cacheKey;
  18326. }
  18327. updateScene( scene ) {
  18328. this.updateEnvironment( scene );
  18329. this.updateFog( scene );
  18330. this.updateBackground( scene );
  18331. }
  18332. get isToneMappingState() {
  18333. return this.renderer.getRenderTarget() ? false : true;
  18334. }
  18335. updateBackground( scene ) {
  18336. const sceneData = this.get( scene );
  18337. const background = scene.background;
  18338. if ( background ) {
  18339. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  18340. if ( sceneData.background !== background || forceUpdate ) {
  18341. let backgroundNode = null;
  18342. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  18343. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  18344. backgroundNode = pmremTexture( background );
  18345. } else {
  18346. let envMap;
  18347. if ( background.isCubeTexture === true ) {
  18348. envMap = cubeTexture( background );
  18349. } else {
  18350. envMap = texture( background );
  18351. }
  18352. backgroundNode = cubeMapNode( envMap );
  18353. }
  18354. } else if ( background.isTexture === true ) {
  18355. backgroundNode = texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  18356. } else if ( background.isColor !== true ) {
  18357. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  18358. }
  18359. sceneData.backgroundNode = backgroundNode;
  18360. sceneData.background = background;
  18361. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  18362. }
  18363. } else if ( sceneData.backgroundNode ) {
  18364. delete sceneData.backgroundNode;
  18365. delete sceneData.background;
  18366. }
  18367. }
  18368. updateFog( scene ) {
  18369. const sceneData = this.get( scene );
  18370. const fog = scene.fog;
  18371. if ( fog ) {
  18372. if ( sceneData.fog !== fog ) {
  18373. let fogNode = null;
  18374. if ( fog.isFogExp2 ) {
  18375. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  18376. const density = reference( 'density', 'float', fog ).setGroup( renderGroup );
  18377. fogNode = densityFog( color, density );
  18378. } else if ( fog.isFog ) {
  18379. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  18380. const near = reference( 'near', 'float', fog ).setGroup( renderGroup );
  18381. const far = reference( 'far', 'float', fog ).setGroup( renderGroup );
  18382. fogNode = rangeFog( color, near, far );
  18383. } else {
  18384. console.error( 'WebGPUNodes: Unsupported fog configuration.', fog );
  18385. }
  18386. sceneData.fogNode = fogNode;
  18387. sceneData.fog = fog;
  18388. }
  18389. } else {
  18390. delete sceneData.fogNode;
  18391. delete sceneData.fog;
  18392. }
  18393. }
  18394. updateEnvironment( scene ) {
  18395. const sceneData = this.get( scene );
  18396. const environment = scene.environment;
  18397. if ( environment ) {
  18398. if ( sceneData.environment !== environment ) {
  18399. let environmentNode = null;
  18400. if ( environment.isCubeTexture === true ) {
  18401. environmentNode = cubeTexture( environment );
  18402. } else if ( environment.isTexture === true ) {
  18403. environmentNode = texture( environment );
  18404. } else {
  18405. console.error( 'Nodes: Unsupported environment configuration.', environment );
  18406. }
  18407. sceneData.environmentNode = environmentNode;
  18408. sceneData.environment = environment;
  18409. }
  18410. } else if ( sceneData.environmentNode ) {
  18411. delete sceneData.environmentNode;
  18412. delete sceneData.environment;
  18413. }
  18414. }
  18415. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  18416. const nodeFrame = this.nodeFrame;
  18417. nodeFrame.renderer = renderer;
  18418. nodeFrame.scene = scene;
  18419. nodeFrame.object = object;
  18420. nodeFrame.camera = camera;
  18421. nodeFrame.material = material;
  18422. return nodeFrame;
  18423. }
  18424. getNodeFrameForRender( renderObject ) {
  18425. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  18426. }
  18427. getOutputCacheKey() {
  18428. const renderer = this.renderer;
  18429. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  18430. }
  18431. hasOutputChange( outputTarget ) {
  18432. const cacheKey = outputNodeMap.get( outputTarget );
  18433. return cacheKey !== this.getOutputCacheKey();
  18434. }
  18435. getOutputNode( outputTexture ) {
  18436. const renderer = this.renderer;
  18437. const cacheKey = this.getOutputCacheKey();
  18438. const output = texture( outputTexture, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  18439. outputNodeMap.set( outputTexture, cacheKey );
  18440. return output;
  18441. }
  18442. updateBefore( renderObject ) {
  18443. const nodeBuilder = renderObject.getNodeBuilderState();
  18444. for ( const node of nodeBuilder.updateBeforeNodes ) {
  18445. // update frame state for each node
  18446. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  18447. }
  18448. }
  18449. updateAfter( renderObject ) {
  18450. const nodeBuilder = renderObject.getNodeBuilderState();
  18451. for ( const node of nodeBuilder.updateAfterNodes ) {
  18452. // update frame state for each node
  18453. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  18454. }
  18455. }
  18456. updateForCompute( computeNode ) {
  18457. const nodeFrame = this.getNodeFrame();
  18458. const nodeBuilder = this.getForCompute( computeNode );
  18459. for ( const node of nodeBuilder.updateNodes ) {
  18460. nodeFrame.updateNode( node );
  18461. }
  18462. }
  18463. updateForRender( renderObject ) {
  18464. const nodeFrame = this.getNodeFrameForRender( renderObject );
  18465. const nodeBuilder = renderObject.getNodeBuilderState();
  18466. for ( const node of nodeBuilder.updateNodes ) {
  18467. nodeFrame.updateNode( node );
  18468. }
  18469. }
  18470. needsRefresh( renderObject ) {
  18471. const nodeFrame = this.getNodeFrameForRender( renderObject );
  18472. const monitor = renderObject.getMonitor();
  18473. return monitor.needsRefresh( renderObject, nodeFrame );
  18474. }
  18475. dispose() {
  18476. super.dispose();
  18477. this.nodeFrame = new NodeFrame();
  18478. this.nodeBuilderCache = new Map();
  18479. }
  18480. }
  18481. const _plane = /*@__PURE__*/ new Plane();
  18482. class ClippingContext {
  18483. constructor( parentContext = null ) {
  18484. this.version = 0;
  18485. this.clipIntersection = null;
  18486. this.cacheKey = '';
  18487. if ( parentContext === null ) {
  18488. this.intersectionPlanes = [];
  18489. this.unionPlanes = [];
  18490. this.viewNormalMatrix = new Matrix3();
  18491. this.clippingGroupContexts = new WeakMap();
  18492. this.shadowPass = false;
  18493. } else {
  18494. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  18495. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  18496. this.shadowPass = parentContext.shadowPass;
  18497. this.viewMatrix = parentContext.viewMatrix;
  18498. }
  18499. this.parentVersion = null;
  18500. }
  18501. projectPlanes( source, destination, offset ) {
  18502. const l = source.length;
  18503. for ( let i = 0; i < l; i ++ ) {
  18504. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  18505. const v = destination[ offset + i ];
  18506. const normal = _plane.normal;
  18507. v.x = - normal.x;
  18508. v.y = - normal.y;
  18509. v.z = - normal.z;
  18510. v.w = _plane.constant;
  18511. }
  18512. }
  18513. updateGlobal( scene, camera ) {
  18514. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowNodeMaterial );
  18515. this.viewMatrix = camera.matrixWorldInverse;
  18516. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  18517. }
  18518. update( parentContext, clippingGroup ) {
  18519. let update = false;
  18520. if ( parentContext.version !== this.parentVersion ) {
  18521. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  18522. this.unionPlanes = Array.from( parentContext.unionPlanes );
  18523. this.parentVersion = parentContext.version;
  18524. }
  18525. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  18526. this.clipIntersection = clippingGroup.clipIntersection;
  18527. if ( this.clipIntersection ) {
  18528. this.unionPlanes.length = parentContext.unionPlanes.length;
  18529. } else {
  18530. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  18531. }
  18532. }
  18533. const srcClippingPlanes = clippingGroup.clippingPlanes;
  18534. const l = srcClippingPlanes.length;
  18535. let dstClippingPlanes;
  18536. let offset;
  18537. if ( this.clipIntersection ) {
  18538. dstClippingPlanes = this.intersectionPlanes;
  18539. offset = parentContext.intersectionPlanes.length;
  18540. } else {
  18541. dstClippingPlanes = this.unionPlanes;
  18542. offset = parentContext.unionPlanes.length;
  18543. }
  18544. if ( dstClippingPlanes.length !== offset + l ) {
  18545. dstClippingPlanes.length = offset + l;
  18546. for ( let i = 0; i < l; i ++ ) {
  18547. dstClippingPlanes[ offset + i ] = new Vector4();
  18548. }
  18549. update = true;
  18550. }
  18551. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  18552. if ( update ) {
  18553. this.version ++;
  18554. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  18555. }
  18556. }
  18557. getGroupContext( clippingGroup ) {
  18558. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  18559. let context = this.clippingGroupContexts.get( clippingGroup );
  18560. if ( context === undefined ) {
  18561. context = new ClippingContext( this );
  18562. this.clippingGroupContexts.set( clippingGroup, context );
  18563. }
  18564. context.update( this, clippingGroup );
  18565. return context;
  18566. }
  18567. get unionClippingCount() {
  18568. return this.unionPlanes.length;
  18569. }
  18570. }
  18571. class RenderBundle {
  18572. constructor( scene, camera ) {
  18573. this.scene = scene;
  18574. this.camera = camera;
  18575. }
  18576. clone() {
  18577. return Object.assign( new this.constructor(), this );
  18578. }
  18579. }
  18580. class RenderBundles {
  18581. constructor() {
  18582. this.lists = new ChainMap();
  18583. }
  18584. get( scene, camera ) {
  18585. const lists = this.lists;
  18586. const keys = [ scene, camera ];
  18587. let list = lists.get( keys );
  18588. if ( list === undefined ) {
  18589. list = new RenderBundle( scene, camera );
  18590. lists.set( keys, list );
  18591. }
  18592. return list;
  18593. }
  18594. dispose() {
  18595. this.lists = new ChainMap();
  18596. }
  18597. }
  18598. class NodeLibrary {
  18599. constructor() {
  18600. this.lightNodes = new WeakMap();
  18601. this.materialNodes = new Map();
  18602. this.toneMappingNodes = new Map();
  18603. }
  18604. fromMaterial( material ) {
  18605. if ( material.isNodeMaterial ) return material;
  18606. let nodeMaterial = null;
  18607. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  18608. if ( nodeMaterialClass !== null ) {
  18609. nodeMaterial = new nodeMaterialClass();
  18610. for ( const key in material ) {
  18611. nodeMaterial[ key ] = material[ key ];
  18612. }
  18613. }
  18614. return nodeMaterial;
  18615. }
  18616. addToneMapping( toneMappingNode, toneMapping ) {
  18617. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  18618. }
  18619. getToneMappingFunction( toneMapping ) {
  18620. return this.toneMappingNodes.get( toneMapping ) || null;
  18621. }
  18622. getMaterialNodeClass( materialType ) {
  18623. return this.materialNodes.get( materialType ) || null;
  18624. }
  18625. addMaterial( materialNodeClass, materialClassType ) {
  18626. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  18627. }
  18628. getLightNodeClass( light ) {
  18629. return this.lightNodes.get( light ) || null;
  18630. }
  18631. addLight( lightNodeClass, lightClass ) {
  18632. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  18633. }
  18634. addType( nodeClass, type, library ) {
  18635. if ( library.has( type ) ) {
  18636. console.warn( `Redefinition of node ${ type }` );
  18637. return;
  18638. }
  18639. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  18640. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  18641. library.set( type, nodeClass );
  18642. }
  18643. addClass( nodeClass, baseClass, library ) {
  18644. if ( library.has( baseClass ) ) {
  18645. console.warn( `Redefinition of node ${ baseClass.name }` );
  18646. return;
  18647. }
  18648. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  18649. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  18650. library.set( baseClass, nodeClass );
  18651. }
  18652. }
  18653. const _defaultLights = /*@__PURE__*/ new LightsNode();
  18654. class Lighting extends ChainMap {
  18655. constructor() {
  18656. super();
  18657. }
  18658. createNode( lights = [] ) {
  18659. return new LightsNode().setLights( lights );
  18660. }
  18661. getNode( scene, camera ) {
  18662. // ignore post-processing
  18663. if ( scene.isQuadMesh ) return _defaultLights;
  18664. // tiled lighting
  18665. const keys = [ scene, camera ];
  18666. let node = this.get( keys );
  18667. if ( node === undefined ) {
  18668. node = this.createNode();
  18669. this.set( keys, node );
  18670. }
  18671. return node;
  18672. }
  18673. }
  18674. const _scene = /*@__PURE__*/ new Scene();
  18675. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  18676. const _screen = /*@__PURE__*/ new Vector4();
  18677. const _frustum = /*@__PURE__*/ new Frustum();
  18678. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  18679. const _vector4 = /*@__PURE__*/ new Vector4();
  18680. class Renderer {
  18681. constructor( backend, parameters = {} ) {
  18682. this.isRenderer = true;
  18683. //
  18684. const {
  18685. logarithmicDepthBuffer = false,
  18686. alpha = true,
  18687. depth = true,
  18688. stencil = false,
  18689. antialias = false,
  18690. samples = 0,
  18691. getFallback = null
  18692. } = parameters;
  18693. // public
  18694. this.domElement = backend.getDomElement();
  18695. this.backend = backend;
  18696. this.samples = samples || ( antialias === true ) ? 4 : 0;
  18697. this.autoClear = true;
  18698. this.autoClearColor = true;
  18699. this.autoClearDepth = true;
  18700. this.autoClearStencil = true;
  18701. this.alpha = alpha;
  18702. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  18703. this.outputColorSpace = SRGBColorSpace;
  18704. this.toneMapping = NoToneMapping;
  18705. this.toneMappingExposure = 1.0;
  18706. this.sortObjects = true;
  18707. this.depth = depth;
  18708. this.stencil = stencil;
  18709. this.info = new Info();
  18710. this.nodes = {
  18711. modelViewMatrix: null,
  18712. modelNormalViewMatrix: null
  18713. };
  18714. this.library = new NodeLibrary();
  18715. this.lighting = new Lighting();
  18716. // internals
  18717. this._getFallback = getFallback;
  18718. this._pixelRatio = 1;
  18719. this._width = this.domElement.width;
  18720. this._height = this.domElement.height;
  18721. this._viewport = new Vector4( 0, 0, this._width, this._height );
  18722. this._scissor = new Vector4( 0, 0, this._width, this._height );
  18723. this._scissorTest = false;
  18724. this._attributes = null;
  18725. this._geometries = null;
  18726. this._nodes = null;
  18727. this._animation = null;
  18728. this._bindings = null;
  18729. this._objects = null;
  18730. this._pipelines = null;
  18731. this._bundles = null;
  18732. this._renderLists = null;
  18733. this._renderContexts = null;
  18734. this._textures = null;
  18735. this._background = null;
  18736. this._quad = new QuadMesh( new NodeMaterial() );
  18737. this._quad.material.type = 'Renderer_output';
  18738. this._currentRenderContext = null;
  18739. this._opaqueSort = null;
  18740. this._transparentSort = null;
  18741. this._frameBufferTarget = null;
  18742. const alphaClear = this.alpha === true ? 0 : 1;
  18743. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  18744. this._clearDepth = 1;
  18745. this._clearStencil = 0;
  18746. this._renderTarget = null;
  18747. this._activeCubeFace = 0;
  18748. this._activeMipmapLevel = 0;
  18749. this._mrt = null;
  18750. this._renderObjectFunction = null;
  18751. this._currentRenderObjectFunction = null;
  18752. this._currentRenderBundle = null;
  18753. this._handleObjectFunction = this._renderObjectDirect;
  18754. this._isDeviceLost = false;
  18755. this.onDeviceLost = this._onDeviceLost;
  18756. this._initialized = false;
  18757. this._initPromise = null;
  18758. this._compilationPromises = null;
  18759. this.transparent = true;
  18760. this.opaque = true;
  18761. this.shadowMap = {
  18762. enabled: false,
  18763. type: PCFShadowMap
  18764. };
  18765. this.xr = {
  18766. enabled: false
  18767. };
  18768. this.debug = {
  18769. checkShaderErrors: true,
  18770. onShaderError: null,
  18771. getShaderAsync: async ( scene, camera, object ) => {
  18772. await this.compileAsync( scene, camera );
  18773. const renderList = this._renderLists.get( scene, camera );
  18774. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  18775. const material = scene.overrideMaterial || object.material;
  18776. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  18777. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  18778. return { fragmentShader, vertexShader };
  18779. }
  18780. };
  18781. }
  18782. async init() {
  18783. if ( this._initialized ) {
  18784. throw new Error( 'Renderer: Backend has already been initialized.' );
  18785. }
  18786. if ( this._initPromise !== null ) {
  18787. return this._initPromise;
  18788. }
  18789. this._initPromise = new Promise( async ( resolve, reject ) => {
  18790. let backend = this.backend;
  18791. try {
  18792. await backend.init( this );
  18793. } catch ( error ) {
  18794. if ( this._getFallback !== null ) {
  18795. // try the fallback
  18796. try {
  18797. this.backend = backend = this._getFallback( error );
  18798. await backend.init( this );
  18799. } catch ( error ) {
  18800. reject( error );
  18801. return;
  18802. }
  18803. } else {
  18804. reject( error );
  18805. return;
  18806. }
  18807. }
  18808. this._nodes = new Nodes( this, backend );
  18809. this._animation = new Animation( this._nodes, this.info );
  18810. this._attributes = new Attributes( backend );
  18811. this._background = new Background( this, this._nodes );
  18812. this._geometries = new Geometries( this._attributes, this.info );
  18813. this._textures = new Textures( this, backend, this.info );
  18814. this._pipelines = new Pipelines( backend, this._nodes );
  18815. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  18816. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  18817. this._renderLists = new RenderLists( this.lighting );
  18818. this._bundles = new RenderBundles();
  18819. this._renderContexts = new RenderContexts();
  18820. //
  18821. this._animation.start();
  18822. this._initialized = true;
  18823. resolve();
  18824. } );
  18825. return this._initPromise;
  18826. }
  18827. get coordinateSystem() {
  18828. return this.backend.coordinateSystem;
  18829. }
  18830. async compileAsync( scene, camera, targetScene = null ) {
  18831. if ( this._isDeviceLost === true ) return;
  18832. if ( this._initialized === false ) await this.init();
  18833. // preserve render tree
  18834. const nodeFrame = this._nodes.nodeFrame;
  18835. const previousRenderId = nodeFrame.renderId;
  18836. const previousRenderContext = this._currentRenderContext;
  18837. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  18838. const previousCompilationPromises = this._compilationPromises;
  18839. //
  18840. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  18841. if ( targetScene === null ) targetScene = scene;
  18842. const renderTarget = this._renderTarget;
  18843. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  18844. const activeMipmapLevel = this._activeMipmapLevel;
  18845. const compilationPromises = [];
  18846. this._currentRenderContext = renderContext;
  18847. this._currentRenderObjectFunction = this.renderObject;
  18848. this._handleObjectFunction = this._createObjectPipeline;
  18849. this._compilationPromises = compilationPromises;
  18850. nodeFrame.renderId ++;
  18851. //
  18852. nodeFrame.update();
  18853. //
  18854. renderContext.depth = this.depth;
  18855. renderContext.stencil = this.stencil;
  18856. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  18857. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  18858. //
  18859. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  18860. //
  18861. const renderList = this._renderLists.get( scene, camera );
  18862. renderList.begin();
  18863. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  18864. // include lights from target scene
  18865. if ( targetScene !== scene ) {
  18866. targetScene.traverseVisible( function ( object ) {
  18867. if ( object.isLight && object.layers.test( camera.layers ) ) {
  18868. renderList.pushLight( object );
  18869. }
  18870. } );
  18871. }
  18872. renderList.finish();
  18873. //
  18874. if ( renderTarget !== null ) {
  18875. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  18876. const renderTargetData = this._textures.get( renderTarget );
  18877. renderContext.textures = renderTargetData.textures;
  18878. renderContext.depthTexture = renderTargetData.depthTexture;
  18879. } else {
  18880. renderContext.textures = null;
  18881. renderContext.depthTexture = null;
  18882. }
  18883. //
  18884. this._nodes.updateScene( sceneRef );
  18885. //
  18886. this._background.update( sceneRef, renderList, renderContext );
  18887. // process render lists
  18888. const opaqueObjects = renderList.opaque;
  18889. const transparentObjects = renderList.transparent;
  18890. const transparentDoublePassObjects = renderList.transparentDoublePass;
  18891. const lightsNode = renderList.lightsNode;
  18892. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  18893. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  18894. // restore render tree
  18895. nodeFrame.renderId = previousRenderId;
  18896. this._currentRenderContext = previousRenderContext;
  18897. this._currentRenderObjectFunction = previousRenderObjectFunction;
  18898. this._compilationPromises = previousCompilationPromises;
  18899. this._handleObjectFunction = this._renderObjectDirect;
  18900. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  18901. await Promise.all( compilationPromises );
  18902. }
  18903. async renderAsync( scene, camera ) {
  18904. if ( this._initialized === false ) await this.init();
  18905. const renderContext = this._renderScene( scene, camera );
  18906. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  18907. }
  18908. async waitForGPU() {
  18909. await this.backend.waitForGPU();
  18910. }
  18911. setMRT( mrt ) {
  18912. this._mrt = mrt;
  18913. return this;
  18914. }
  18915. getMRT() {
  18916. return this._mrt;
  18917. }
  18918. _onDeviceLost( info ) {
  18919. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  18920. if ( info.reason ) {
  18921. errorMessage += `\nReason: ${info.reason}`;
  18922. }
  18923. console.error( errorMessage );
  18924. this._isDeviceLost = true;
  18925. }
  18926. _renderBundle( bundle, sceneRef, lightsNode ) {
  18927. const { bundleGroup, camera, renderList } = bundle;
  18928. const renderContext = this._currentRenderContext;
  18929. //
  18930. const renderBundle = this._bundles.get( bundleGroup, camera );
  18931. const renderBundleData = this.backend.get( renderBundle );
  18932. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  18933. //
  18934. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  18935. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  18936. renderBundleData.renderContexts.add( renderContext );
  18937. if ( renderBundleNeedsUpdate ) {
  18938. this.backend.beginBundle( renderContext );
  18939. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  18940. renderBundleData.renderObjects = [];
  18941. }
  18942. this._currentRenderBundle = renderBundle;
  18943. const opaqueObjects = renderList.opaque;
  18944. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  18945. this._currentRenderBundle = null;
  18946. //
  18947. this.backend.finishBundle( renderContext, renderBundle );
  18948. renderBundleData.version = bundleGroup.version;
  18949. } else {
  18950. const { renderObjects } = renderBundleData;
  18951. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  18952. const renderObject = renderObjects[ i ];
  18953. if ( this._nodes.needsRefresh( renderObject ) ) {
  18954. this._nodes.updateBefore( renderObject );
  18955. this._nodes.updateForRender( renderObject );
  18956. this._bindings.updateForRender( renderObject );
  18957. this._nodes.updateAfter( renderObject );
  18958. }
  18959. }
  18960. }
  18961. this.backend.addBundle( renderContext, renderBundle );
  18962. }
  18963. render( scene, camera ) {
  18964. if ( this._initialized === false ) {
  18965. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  18966. return this.renderAsync( scene, camera );
  18967. }
  18968. this._renderScene( scene, camera );
  18969. }
  18970. _getFrameBufferTarget() {
  18971. const { currentToneMapping, currentColorSpace } = this;
  18972. const useToneMapping = currentToneMapping !== NoToneMapping;
  18973. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  18974. if ( useToneMapping === false && useColorSpace === false ) return null;
  18975. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  18976. const { depth, stencil } = this;
  18977. let frameBufferTarget = this._frameBufferTarget;
  18978. if ( frameBufferTarget === null ) {
  18979. frameBufferTarget = new RenderTarget( width, height, {
  18980. depthBuffer: depth,
  18981. stencilBuffer: stencil,
  18982. type: HalfFloatType, // FloatType
  18983. format: RGBAFormat,
  18984. colorSpace: LinearSRGBColorSpace,
  18985. generateMipmaps: false,
  18986. minFilter: LinearFilter,
  18987. magFilter: LinearFilter,
  18988. samples: this.samples
  18989. } );
  18990. frameBufferTarget.isPostProcessingRenderTarget = true;
  18991. this._frameBufferTarget = frameBufferTarget;
  18992. }
  18993. frameBufferTarget.depthBuffer = depth;
  18994. frameBufferTarget.stencilBuffer = stencil;
  18995. frameBufferTarget.setSize( width, height );
  18996. frameBufferTarget.viewport.copy( this._viewport );
  18997. frameBufferTarget.scissor.copy( this._scissor );
  18998. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  18999. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  19000. frameBufferTarget.scissorTest = this._scissorTest;
  19001. return frameBufferTarget;
  19002. }
  19003. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  19004. if ( this._isDeviceLost === true ) return;
  19005. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  19006. // preserve render tree
  19007. const nodeFrame = this._nodes.nodeFrame;
  19008. const previousRenderId = nodeFrame.renderId;
  19009. const previousRenderContext = this._currentRenderContext;
  19010. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  19011. //
  19012. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  19013. const outputRenderTarget = this._renderTarget;
  19014. const activeCubeFace = this._activeCubeFace;
  19015. const activeMipmapLevel = this._activeMipmapLevel;
  19016. //
  19017. let renderTarget;
  19018. if ( frameBufferTarget !== null ) {
  19019. renderTarget = frameBufferTarget;
  19020. this.setRenderTarget( renderTarget );
  19021. } else {
  19022. renderTarget = outputRenderTarget;
  19023. }
  19024. //
  19025. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  19026. this._currentRenderContext = renderContext;
  19027. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  19028. //
  19029. this.info.calls ++;
  19030. this.info.render.calls ++;
  19031. this.info.render.frameCalls ++;
  19032. nodeFrame.renderId = this.info.calls;
  19033. //
  19034. const coordinateSystem = this.coordinateSystem;
  19035. if ( camera.coordinateSystem !== coordinateSystem ) {
  19036. camera.coordinateSystem = coordinateSystem;
  19037. camera.updateProjectionMatrix();
  19038. }
  19039. //
  19040. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  19041. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  19042. //
  19043. let viewport = this._viewport;
  19044. let scissor = this._scissor;
  19045. let pixelRatio = this._pixelRatio;
  19046. if ( renderTarget !== null ) {
  19047. viewport = renderTarget.viewport;
  19048. scissor = renderTarget.scissor;
  19049. pixelRatio = 1;
  19050. }
  19051. this.getDrawingBufferSize( _drawingBufferSize );
  19052. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  19053. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  19054. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  19055. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  19056. renderContext.viewportValue.width >>= activeMipmapLevel;
  19057. renderContext.viewportValue.height >>= activeMipmapLevel;
  19058. renderContext.viewportValue.minDepth = minDepth;
  19059. renderContext.viewportValue.maxDepth = maxDepth;
  19060. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  19061. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  19062. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  19063. renderContext.scissorValue.width >>= activeMipmapLevel;
  19064. renderContext.scissorValue.height >>= activeMipmapLevel;
  19065. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  19066. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  19067. //
  19068. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  19069. //
  19070. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  19071. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  19072. const renderList = this._renderLists.get( scene, camera );
  19073. renderList.begin();
  19074. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  19075. renderList.finish();
  19076. if ( this.sortObjects === true ) {
  19077. renderList.sort( this._opaqueSort, this._transparentSort );
  19078. }
  19079. //
  19080. if ( renderTarget !== null ) {
  19081. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  19082. const renderTargetData = this._textures.get( renderTarget );
  19083. renderContext.textures = renderTargetData.textures;
  19084. renderContext.depthTexture = renderTargetData.depthTexture;
  19085. renderContext.width = renderTargetData.width;
  19086. renderContext.height = renderTargetData.height;
  19087. renderContext.renderTarget = renderTarget;
  19088. renderContext.depth = renderTarget.depthBuffer;
  19089. renderContext.stencil = renderTarget.stencilBuffer;
  19090. } else {
  19091. renderContext.textures = null;
  19092. renderContext.depthTexture = null;
  19093. renderContext.width = this.domElement.width;
  19094. renderContext.height = this.domElement.height;
  19095. renderContext.depth = this.depth;
  19096. renderContext.stencil = this.stencil;
  19097. }
  19098. renderContext.width >>= activeMipmapLevel;
  19099. renderContext.height >>= activeMipmapLevel;
  19100. renderContext.activeCubeFace = activeCubeFace;
  19101. renderContext.activeMipmapLevel = activeMipmapLevel;
  19102. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  19103. //
  19104. this._nodes.updateScene( sceneRef );
  19105. //
  19106. this._background.update( sceneRef, renderList, renderContext );
  19107. //
  19108. this.backend.beginRender( renderContext );
  19109. // process render lists
  19110. const {
  19111. bundles,
  19112. lightsNode,
  19113. transparentDoublePass: transparentDoublePassObjects,
  19114. transparent: transparentObjects,
  19115. opaque: opaqueObjects
  19116. } = renderList;
  19117. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  19118. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  19119. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  19120. // finish render pass
  19121. this.backend.finishRender( renderContext );
  19122. // restore render tree
  19123. nodeFrame.renderId = previousRenderId;
  19124. this._currentRenderContext = previousRenderContext;
  19125. this._currentRenderObjectFunction = previousRenderObjectFunction;
  19126. //
  19127. if ( frameBufferTarget !== null ) {
  19128. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  19129. const quad = this._quad;
  19130. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  19131. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  19132. quad.material.needsUpdate = true;
  19133. }
  19134. this._renderScene( quad, quad.camera, false );
  19135. }
  19136. //
  19137. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  19138. //
  19139. return renderContext;
  19140. }
  19141. getMaxAnisotropy() {
  19142. return this.backend.getMaxAnisotropy();
  19143. }
  19144. getActiveCubeFace() {
  19145. return this._activeCubeFace;
  19146. }
  19147. getActiveMipmapLevel() {
  19148. return this._activeMipmapLevel;
  19149. }
  19150. async setAnimationLoop( callback ) {
  19151. if ( this._initialized === false ) await this.init();
  19152. this._animation.setAnimationLoop( callback );
  19153. }
  19154. async getArrayBufferAsync( attribute ) {
  19155. return await this.backend.getArrayBufferAsync( attribute );
  19156. }
  19157. getContext() {
  19158. return this.backend.getContext();
  19159. }
  19160. getPixelRatio() {
  19161. return this._pixelRatio;
  19162. }
  19163. getDrawingBufferSize( target ) {
  19164. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  19165. }
  19166. getSize( target ) {
  19167. return target.set( this._width, this._height );
  19168. }
  19169. setPixelRatio( value = 1 ) {
  19170. if ( this._pixelRatio === value ) return;
  19171. this._pixelRatio = value;
  19172. this.setSize( this._width, this._height, false );
  19173. }
  19174. setDrawingBufferSize( width, height, pixelRatio ) {
  19175. this._width = width;
  19176. this._height = height;
  19177. this._pixelRatio = pixelRatio;
  19178. this.domElement.width = Math.floor( width * pixelRatio );
  19179. this.domElement.height = Math.floor( height * pixelRatio );
  19180. this.setViewport( 0, 0, width, height );
  19181. if ( this._initialized ) this.backend.updateSize();
  19182. }
  19183. setSize( width, height, updateStyle = true ) {
  19184. this._width = width;
  19185. this._height = height;
  19186. this.domElement.width = Math.floor( width * this._pixelRatio );
  19187. this.domElement.height = Math.floor( height * this._pixelRatio );
  19188. if ( updateStyle === true ) {
  19189. this.domElement.style.width = width + 'px';
  19190. this.domElement.style.height = height + 'px';
  19191. }
  19192. this.setViewport( 0, 0, width, height );
  19193. if ( this._initialized ) this.backend.updateSize();
  19194. }
  19195. setOpaqueSort( method ) {
  19196. this._opaqueSort = method;
  19197. }
  19198. setTransparentSort( method ) {
  19199. this._transparentSort = method;
  19200. }
  19201. getScissor( target ) {
  19202. const scissor = this._scissor;
  19203. target.x = scissor.x;
  19204. target.y = scissor.y;
  19205. target.width = scissor.width;
  19206. target.height = scissor.height;
  19207. return target;
  19208. }
  19209. setScissor( x, y, width, height ) {
  19210. const scissor = this._scissor;
  19211. if ( x.isVector4 ) {
  19212. scissor.copy( x );
  19213. } else {
  19214. scissor.set( x, y, width, height );
  19215. }
  19216. }
  19217. getScissorTest() {
  19218. return this._scissorTest;
  19219. }
  19220. setScissorTest( boolean ) {
  19221. this._scissorTest = boolean;
  19222. this.backend.setScissorTest( boolean );
  19223. }
  19224. getViewport( target ) {
  19225. return target.copy( this._viewport );
  19226. }
  19227. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  19228. const viewport = this._viewport;
  19229. if ( x.isVector4 ) {
  19230. viewport.copy( x );
  19231. } else {
  19232. viewport.set( x, y, width, height );
  19233. }
  19234. viewport.minDepth = minDepth;
  19235. viewport.maxDepth = maxDepth;
  19236. }
  19237. getClearColor( target ) {
  19238. return target.copy( this._clearColor );
  19239. }
  19240. setClearColor( color, alpha = 1 ) {
  19241. this._clearColor.set( color );
  19242. this._clearColor.a = alpha;
  19243. }
  19244. getClearAlpha() {
  19245. return this._clearColor.a;
  19246. }
  19247. setClearAlpha( alpha ) {
  19248. this._clearColor.a = alpha;
  19249. }
  19250. getClearDepth() {
  19251. return this._clearDepth;
  19252. }
  19253. setClearDepth( depth ) {
  19254. this._clearDepth = depth;
  19255. }
  19256. getClearStencil() {
  19257. return this._clearStencil;
  19258. }
  19259. setClearStencil( stencil ) {
  19260. this._clearStencil = stencil;
  19261. }
  19262. isOccluded( object ) {
  19263. const renderContext = this._currentRenderContext;
  19264. return renderContext && this.backend.isOccluded( renderContext, object );
  19265. }
  19266. clear( color = true, depth = true, stencil = true ) {
  19267. if ( this._initialized === false ) {
  19268. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  19269. return this.clearAsync( color, depth, stencil );
  19270. }
  19271. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  19272. let renderTargetData = null;
  19273. if ( renderTarget !== null ) {
  19274. this._textures.updateRenderTarget( renderTarget );
  19275. renderTargetData = this._textures.get( renderTarget );
  19276. }
  19277. this.backend.clear( color, depth, stencil, renderTargetData );
  19278. if ( renderTarget !== null && this._renderTarget === null ) {
  19279. // If a color space transform or tone mapping is required,
  19280. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  19281. const quad = this._quad;
  19282. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  19283. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  19284. quad.material.needsUpdate = true;
  19285. }
  19286. this._renderScene( quad, quad.camera, false );
  19287. }
  19288. }
  19289. clearColor() {
  19290. return this.clear( true, false, false );
  19291. }
  19292. clearDepth() {
  19293. return this.clear( false, true, false );
  19294. }
  19295. clearStencil() {
  19296. return this.clear( false, false, true );
  19297. }
  19298. async clearAsync( color = true, depth = true, stencil = true ) {
  19299. if ( this._initialized === false ) await this.init();
  19300. this.clear( color, depth, stencil );
  19301. }
  19302. clearColorAsync() {
  19303. return this.clearAsync( true, false, false );
  19304. }
  19305. clearDepthAsync() {
  19306. return this.clearAsync( false, true, false );
  19307. }
  19308. clearStencilAsync() {
  19309. return this.clearAsync( false, false, true );
  19310. }
  19311. get currentToneMapping() {
  19312. return this._renderTarget !== null ? NoToneMapping : this.toneMapping;
  19313. }
  19314. get currentColorSpace() {
  19315. return this._renderTarget !== null ? LinearSRGBColorSpace : this.outputColorSpace;
  19316. }
  19317. dispose() {
  19318. this.info.dispose();
  19319. this.backend.dispose();
  19320. this._animation.dispose();
  19321. this._objects.dispose();
  19322. this._pipelines.dispose();
  19323. this._nodes.dispose();
  19324. this._bindings.dispose();
  19325. this._renderLists.dispose();
  19326. this._renderContexts.dispose();
  19327. this._textures.dispose();
  19328. this.setRenderTarget( null );
  19329. this.setAnimationLoop( null );
  19330. }
  19331. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  19332. this._renderTarget = renderTarget;
  19333. this._activeCubeFace = activeCubeFace;
  19334. this._activeMipmapLevel = activeMipmapLevel;
  19335. }
  19336. getRenderTarget() {
  19337. return this._renderTarget;
  19338. }
  19339. setRenderObjectFunction( renderObjectFunction ) {
  19340. this._renderObjectFunction = renderObjectFunction;
  19341. }
  19342. getRenderObjectFunction() {
  19343. return this._renderObjectFunction;
  19344. }
  19345. compute( computeNodes ) {
  19346. if ( this.isDeviceLost === true ) return;
  19347. if ( this._initialized === false ) {
  19348. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  19349. return this.computeAsync( computeNodes );
  19350. }
  19351. //
  19352. const nodeFrame = this._nodes.nodeFrame;
  19353. const previousRenderId = nodeFrame.renderId;
  19354. //
  19355. this.info.calls ++;
  19356. this.info.compute.calls ++;
  19357. this.info.compute.frameCalls ++;
  19358. nodeFrame.renderId = this.info.calls;
  19359. //
  19360. const backend = this.backend;
  19361. const pipelines = this._pipelines;
  19362. const bindings = this._bindings;
  19363. const nodes = this._nodes;
  19364. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  19365. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  19366. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  19367. }
  19368. backend.beginCompute( computeNodes );
  19369. for ( const computeNode of computeList ) {
  19370. // onInit
  19371. if ( pipelines.has( computeNode ) === false ) {
  19372. const dispose = () => {
  19373. computeNode.removeEventListener( 'dispose', dispose );
  19374. pipelines.delete( computeNode );
  19375. bindings.delete( computeNode );
  19376. nodes.delete( computeNode );
  19377. };
  19378. computeNode.addEventListener( 'dispose', dispose );
  19379. //
  19380. const onInitFn = computeNode.onInitFunction;
  19381. if ( onInitFn !== null ) {
  19382. onInitFn.call( computeNode, { renderer: this } );
  19383. }
  19384. }
  19385. nodes.updateForCompute( computeNode );
  19386. bindings.updateForCompute( computeNode );
  19387. const computeBindings = bindings.getForCompute( computeNode );
  19388. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  19389. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  19390. }
  19391. backend.finishCompute( computeNodes );
  19392. //
  19393. nodeFrame.renderId = previousRenderId;
  19394. }
  19395. async computeAsync( computeNodes ) {
  19396. if ( this._initialized === false ) await this.init();
  19397. this.compute( computeNodes );
  19398. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  19399. }
  19400. async hasFeatureAsync( name ) {
  19401. if ( this._initialized === false ) await this.init();
  19402. return this.backend.hasFeature( name );
  19403. }
  19404. hasFeature( name ) {
  19405. if ( this._initialized === false ) {
  19406. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  19407. return false;
  19408. }
  19409. return this.backend.hasFeature( name );
  19410. }
  19411. hasInitialized() {
  19412. return this._initialized;
  19413. }
  19414. async initTextureAsync( texture ) {
  19415. if ( this._initialized === false ) await this.init();
  19416. this._textures.updateTexture( texture );
  19417. }
  19418. initTexture( texture ) {
  19419. if ( this._initialized === false ) {
  19420. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  19421. return false;
  19422. }
  19423. this._textures.updateTexture( texture );
  19424. }
  19425. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  19426. if ( rectangle !== null ) {
  19427. if ( rectangle.isVector2 ) {
  19428. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  19429. } else if ( rectangle.isVector4 ) {
  19430. rectangle = _vector4.copy( rectangle ).floor();
  19431. } else {
  19432. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  19433. return;
  19434. }
  19435. } else {
  19436. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  19437. }
  19438. //
  19439. let renderContext = this._currentRenderContext;
  19440. let renderTarget;
  19441. if ( renderContext !== null ) {
  19442. renderTarget = renderContext.renderTarget;
  19443. } else {
  19444. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  19445. if ( renderTarget !== null ) {
  19446. this._textures.updateRenderTarget( renderTarget );
  19447. renderContext = this._textures.get( renderTarget );
  19448. }
  19449. }
  19450. //
  19451. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  19452. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  19453. }
  19454. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  19455. this._textures.updateTexture( srcTexture );
  19456. this._textures.updateTexture( dstTexture );
  19457. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  19458. }
  19459. readRenderTargetPixelsAsync( renderTarget, x, y, width, height, index = 0, faceIndex = 0 ) {
  19460. return this.backend.copyTextureToBuffer( renderTarget.textures[ index ], x, y, width, height, faceIndex );
  19461. }
  19462. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  19463. if ( object.visible === false ) return;
  19464. const visible = object.layers.test( camera.layers );
  19465. if ( visible ) {
  19466. if ( object.isGroup ) {
  19467. groupOrder = object.renderOrder;
  19468. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  19469. } else if ( object.isLOD ) {
  19470. if ( object.autoUpdate === true ) object.update( camera );
  19471. } else if ( object.isLight ) {
  19472. renderList.pushLight( object );
  19473. } else if ( object.isSprite ) {
  19474. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  19475. if ( this.sortObjects === true ) {
  19476. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  19477. }
  19478. const { geometry, material } = object;
  19479. if ( material.visible ) {
  19480. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  19481. }
  19482. }
  19483. } else if ( object.isLineLoop ) {
  19484. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  19485. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  19486. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  19487. const { geometry, material } = object;
  19488. if ( this.sortObjects === true ) {
  19489. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19490. _vector4
  19491. .copy( geometry.boundingSphere.center )
  19492. .applyMatrix4( object.matrixWorld )
  19493. .applyMatrix4( _projScreenMatrix );
  19494. }
  19495. if ( Array.isArray( material ) ) {
  19496. const groups = geometry.groups;
  19497. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  19498. const group = groups[ i ];
  19499. const groupMaterial = material[ group.materialIndex ];
  19500. if ( groupMaterial && groupMaterial.visible ) {
  19501. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  19502. }
  19503. }
  19504. } else if ( material.visible ) {
  19505. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  19506. }
  19507. }
  19508. }
  19509. }
  19510. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  19511. const baseRenderList = renderList;
  19512. // replace render list
  19513. renderList = this._renderLists.get( object, camera );
  19514. renderList.begin();
  19515. baseRenderList.pushBundle( {
  19516. bundleGroup: object,
  19517. camera,
  19518. renderList,
  19519. } );
  19520. renderList.finish();
  19521. }
  19522. const children = object.children;
  19523. for ( let i = 0, l = children.length; i < l; i ++ ) {
  19524. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  19525. }
  19526. }
  19527. _renderBundles( bundles, sceneRef, lightsNode ) {
  19528. for ( const bundle of bundles ) {
  19529. this._renderBundle( bundle, sceneRef, lightsNode );
  19530. }
  19531. }
  19532. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  19533. if ( doublePassList.length > 0 ) {
  19534. // render back side
  19535. for ( const { material } of doublePassList ) {
  19536. material.side = BackSide;
  19537. }
  19538. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  19539. // render front side
  19540. for ( const { material } of doublePassList ) {
  19541. material.side = FrontSide;
  19542. }
  19543. this._renderObjects( renderList, camera, scene, lightsNode );
  19544. // restore
  19545. for ( const { material } of doublePassList ) {
  19546. material.side = DoubleSide;
  19547. }
  19548. } else {
  19549. this._renderObjects( renderList, camera, scene, lightsNode );
  19550. }
  19551. }
  19552. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  19553. // process renderable objects
  19554. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  19555. const renderItem = renderList[ i ];
  19556. // @TODO: Add support for multiple materials per object. This will require to extract
  19557. // the material from the renderItem object and pass it with its group data to renderObject().
  19558. const { object, geometry, material, group, clippingContext } = renderItem;
  19559. if ( camera.isArrayCamera ) {
  19560. const cameras = camera.cameras;
  19561. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  19562. const camera2 = cameras[ j ];
  19563. if ( object.layers.test( camera2.layers ) ) {
  19564. const vp = camera2.viewport;
  19565. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  19566. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  19567. const viewportValue = this._currentRenderContext.viewportValue;
  19568. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  19569. viewportValue.minDepth = minDepth;
  19570. viewportValue.maxDepth = maxDepth;
  19571. this.backend.updateViewport( this._currentRenderContext );
  19572. this._currentRenderObjectFunction( object, scene, camera2, geometry, material, group, lightsNode, clippingContext, passId );
  19573. }
  19574. }
  19575. } else {
  19576. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  19577. }
  19578. }
  19579. }
  19580. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  19581. let overridePositionNode;
  19582. let overrideColorNode;
  19583. let overrideDepthNode;
  19584. //
  19585. object.onBeforeRender( this, scene, camera, geometry, material, group );
  19586. //
  19587. if ( scene.overrideMaterial !== null ) {
  19588. const overrideMaterial = scene.overrideMaterial;
  19589. if ( material.positionNode && material.positionNode.isNode ) {
  19590. overridePositionNode = overrideMaterial.positionNode;
  19591. overrideMaterial.positionNode = material.positionNode;
  19592. }
  19593. overrideMaterial.alphaTest = material.alphaTest;
  19594. overrideMaterial.alphaMap = material.alphaMap;
  19595. if ( overrideMaterial.isShadowNodeMaterial ) {
  19596. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  19597. if ( material.depthNode && material.depthNode.isNode ) {
  19598. overrideDepthNode = overrideMaterial.depthNode;
  19599. overrideMaterial.depthNode = material.depthNode;
  19600. }
  19601. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  19602. overrideColorNode = overrideMaterial.colorNode;
  19603. overrideMaterial.colorNode = material.castShadowNode;
  19604. }
  19605. }
  19606. material = overrideMaterial;
  19607. }
  19608. //
  19609. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  19610. material.side = BackSide;
  19611. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  19612. material.side = FrontSide;
  19613. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  19614. material.side = DoubleSide;
  19615. } else {
  19616. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  19617. }
  19618. //
  19619. if ( overridePositionNode !== undefined ) {
  19620. scene.overrideMaterial.positionNode = overridePositionNode;
  19621. }
  19622. if ( overrideDepthNode !== undefined ) {
  19623. scene.overrideMaterial.depthNode = overrideDepthNode;
  19624. }
  19625. if ( overrideColorNode !== undefined ) {
  19626. scene.overrideMaterial.colorNode = overrideColorNode;
  19627. }
  19628. //
  19629. object.onAfterRender( this, scene, camera, geometry, material, group );
  19630. }
  19631. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  19632. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  19633. renderObject.drawRange = object.geometry.drawRange;
  19634. renderObject.group = group;
  19635. //
  19636. const needsRefresh = this._nodes.needsRefresh( renderObject );
  19637. if ( needsRefresh ) {
  19638. this._nodes.updateBefore( renderObject );
  19639. this._geometries.updateForRender( renderObject );
  19640. this._nodes.updateForRender( renderObject );
  19641. this._bindings.updateForRender( renderObject );
  19642. }
  19643. this._pipelines.updateForRender( renderObject );
  19644. //
  19645. if ( this._currentRenderBundle !== null ) {
  19646. const renderBundleData = this.backend.get( this._currentRenderBundle );
  19647. renderBundleData.renderObjects.push( renderObject );
  19648. renderObject.bundle = this._currentRenderBundle.scene;
  19649. }
  19650. this.backend.draw( renderObject, this.info );
  19651. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  19652. }
  19653. _createObjectPipeline( object, material, scene, camera, lightsNode, clippingContext, passId ) {
  19654. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  19655. //
  19656. this._nodes.updateBefore( renderObject );
  19657. this._geometries.updateForRender( renderObject );
  19658. this._nodes.updateForRender( renderObject );
  19659. this._bindings.updateForRender( renderObject );
  19660. this._pipelines.getForRender( renderObject, this._compilationPromises );
  19661. this._nodes.updateAfter( renderObject );
  19662. }
  19663. get compile() {
  19664. return this.compileAsync;
  19665. }
  19666. }
  19667. class Binding {
  19668. constructor( name = '' ) {
  19669. this.name = name;
  19670. this.visibility = 0;
  19671. }
  19672. setVisibility( visibility ) {
  19673. this.visibility |= visibility;
  19674. }
  19675. clone() {
  19676. return Object.assign( new this.constructor(), this );
  19677. }
  19678. }
  19679. function getFloatLength( floatLength ) {
  19680. // ensure chunk size alignment (STD140 layout)
  19681. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  19682. }
  19683. class Buffer extends Binding {
  19684. constructor( name, buffer = null ) {
  19685. super( name );
  19686. this.isBuffer = true;
  19687. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  19688. this._buffer = buffer;
  19689. }
  19690. get byteLength() {
  19691. return getFloatLength( this._buffer.byteLength );
  19692. }
  19693. get buffer() {
  19694. return this._buffer;
  19695. }
  19696. update() {
  19697. return true;
  19698. }
  19699. }
  19700. class UniformBuffer extends Buffer {
  19701. constructor( name, buffer = null ) {
  19702. super( name, buffer );
  19703. this.isUniformBuffer = true;
  19704. }
  19705. }
  19706. let _id$4 = 0;
  19707. class NodeUniformBuffer extends UniformBuffer {
  19708. constructor( nodeUniform, groupNode ) {
  19709. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  19710. this.nodeUniform = nodeUniform;
  19711. this.groupNode = groupNode;
  19712. }
  19713. get buffer() {
  19714. return this.nodeUniform.value;
  19715. }
  19716. }
  19717. class UniformsGroup extends UniformBuffer {
  19718. constructor( name ) {
  19719. super( name );
  19720. this.isUniformsGroup = true;
  19721. this._values = null;
  19722. // the order of uniforms in this array must match the order of uniforms in the shader
  19723. this.uniforms = [];
  19724. }
  19725. addUniform( uniform ) {
  19726. this.uniforms.push( uniform );
  19727. return this;
  19728. }
  19729. removeUniform( uniform ) {
  19730. const index = this.uniforms.indexOf( uniform );
  19731. if ( index !== - 1 ) {
  19732. this.uniforms.splice( index, 1 );
  19733. }
  19734. return this;
  19735. }
  19736. get values() {
  19737. if ( this._values === null ) {
  19738. this._values = Array.from( this.buffer );
  19739. }
  19740. return this._values;
  19741. }
  19742. get buffer() {
  19743. let buffer = this._buffer;
  19744. if ( buffer === null ) {
  19745. const byteLength = this.byteLength;
  19746. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  19747. this._buffer = buffer;
  19748. }
  19749. return buffer;
  19750. }
  19751. get byteLength() {
  19752. let offset = 0; // global buffer offset in bytes
  19753. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  19754. const uniform = this.uniforms[ i ];
  19755. const { boundary, itemSize } = uniform;
  19756. // offset within a single chunk in bytes
  19757. const chunkOffset = offset % GPU_CHUNK_BYTES;
  19758. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  19759. // conformance tests
  19760. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  19761. // check for chunk overflow
  19762. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  19763. } else if ( chunkOffset % boundary !== 0 ) {
  19764. // check for correct alignment
  19765. offset += ( chunkOffset % boundary );
  19766. }
  19767. uniform.offset = ( offset / this.bytesPerElement );
  19768. offset += ( itemSize * this.bytesPerElement );
  19769. }
  19770. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  19771. }
  19772. update() {
  19773. let updated = false;
  19774. for ( const uniform of this.uniforms ) {
  19775. if ( this.updateByType( uniform ) === true ) {
  19776. updated = true;
  19777. }
  19778. }
  19779. return updated;
  19780. }
  19781. updateByType( uniform ) {
  19782. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  19783. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  19784. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  19785. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  19786. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  19787. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  19788. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  19789. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  19790. }
  19791. updateNumber( uniform ) {
  19792. let updated = false;
  19793. const a = this.values;
  19794. const v = uniform.getValue();
  19795. const offset = uniform.offset;
  19796. const type = uniform.getType();
  19797. if ( a[ offset ] !== v ) {
  19798. const b = this._getBufferForType( type );
  19799. b[ offset ] = a[ offset ] = v;
  19800. updated = true;
  19801. }
  19802. return updated;
  19803. }
  19804. updateVector2( uniform ) {
  19805. let updated = false;
  19806. const a = this.values;
  19807. const v = uniform.getValue();
  19808. const offset = uniform.offset;
  19809. const type = uniform.getType();
  19810. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  19811. const b = this._getBufferForType( type );
  19812. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  19813. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  19814. updated = true;
  19815. }
  19816. return updated;
  19817. }
  19818. updateVector3( uniform ) {
  19819. let updated = false;
  19820. const a = this.values;
  19821. const v = uniform.getValue();
  19822. const offset = uniform.offset;
  19823. const type = uniform.getType();
  19824. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  19825. const b = this._getBufferForType( type );
  19826. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  19827. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  19828. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  19829. updated = true;
  19830. }
  19831. return updated;
  19832. }
  19833. updateVector4( uniform ) {
  19834. let updated = false;
  19835. const a = this.values;
  19836. const v = uniform.getValue();
  19837. const offset = uniform.offset;
  19838. const type = uniform.getType();
  19839. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  19840. const b = this._getBufferForType( type );
  19841. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  19842. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  19843. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  19844. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  19845. updated = true;
  19846. }
  19847. return updated;
  19848. }
  19849. updateColor( uniform ) {
  19850. let updated = false;
  19851. const a = this.values;
  19852. const c = uniform.getValue();
  19853. const offset = uniform.offset;
  19854. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  19855. const b = this.buffer;
  19856. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  19857. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  19858. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  19859. updated = true;
  19860. }
  19861. return updated;
  19862. }
  19863. updateMatrix3( uniform ) {
  19864. let updated = false;
  19865. const a = this.values;
  19866. const e = uniform.getValue().elements;
  19867. const offset = uniform.offset;
  19868. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  19869. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  19870. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  19871. const b = this.buffer;
  19872. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  19873. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  19874. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  19875. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  19876. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  19877. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  19878. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  19879. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  19880. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  19881. updated = true;
  19882. }
  19883. return updated;
  19884. }
  19885. updateMatrix4( uniform ) {
  19886. let updated = false;
  19887. const a = this.values;
  19888. const e = uniform.getValue().elements;
  19889. const offset = uniform.offset;
  19890. if ( arraysEqual( a, e, offset ) === false ) {
  19891. const b = this.buffer;
  19892. b.set( e, offset );
  19893. setArray( a, e, offset );
  19894. updated = true;
  19895. }
  19896. return updated;
  19897. }
  19898. _getBufferForType( type ) {
  19899. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  19900. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  19901. return this.buffer;
  19902. }
  19903. }
  19904. function setArray( a, b, offset ) {
  19905. for ( let i = 0, l = b.length; i < l; i ++ ) {
  19906. a[ offset + i ] = b[ i ];
  19907. }
  19908. }
  19909. function arraysEqual( a, b, offset ) {
  19910. for ( let i = 0, l = b.length; i < l; i ++ ) {
  19911. if ( a[ offset + i ] !== b[ i ] ) return false;
  19912. }
  19913. return true;
  19914. }
  19915. let _id$3 = 0;
  19916. class NodeUniformsGroup extends UniformsGroup {
  19917. constructor( name, groupNode ) {
  19918. super( name );
  19919. this.id = _id$3 ++;
  19920. this.groupNode = groupNode;
  19921. this.isNodeUniformsGroup = true;
  19922. }
  19923. getNodes() {
  19924. const nodes = [];
  19925. for ( const uniform of this.uniforms ) {
  19926. const node = uniform.nodeUniform.node;
  19927. if ( ! node ) throw new Error( 'NodeUniformsGroup: Uniform has no node.' );
  19928. nodes.push( node );
  19929. }
  19930. return nodes;
  19931. }
  19932. }
  19933. let _id$2 = 0;
  19934. class SampledTexture extends Binding {
  19935. constructor( name, texture ) {
  19936. super( name );
  19937. this.id = _id$2 ++;
  19938. this.texture = texture;
  19939. this.version = texture ? texture.version : 0;
  19940. this.store = false;
  19941. this.generation = null;
  19942. this.isSampledTexture = true;
  19943. }
  19944. needsBindingsUpdate( generation ) {
  19945. const { texture } = this;
  19946. if ( generation !== this.generation ) {
  19947. this.generation = generation;
  19948. return true;
  19949. }
  19950. return texture.isVideoTexture;
  19951. }
  19952. update() {
  19953. const { texture, version } = this;
  19954. if ( version !== texture.version ) {
  19955. this.version = texture.version;
  19956. return true;
  19957. }
  19958. return false;
  19959. }
  19960. }
  19961. class NodeSampledTexture extends SampledTexture {
  19962. constructor( name, textureNode, groupNode, access = null ) {
  19963. super( name, textureNode ? textureNode.value : null );
  19964. this.textureNode = textureNode;
  19965. this.groupNode = groupNode;
  19966. this.access = access;
  19967. }
  19968. needsBindingsUpdate( generation ) {
  19969. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  19970. }
  19971. update() {
  19972. const { textureNode } = this;
  19973. if ( this.texture !== textureNode.value ) {
  19974. this.texture = textureNode.value;
  19975. return true;
  19976. }
  19977. return super.update();
  19978. }
  19979. }
  19980. class NodeSampledCubeTexture extends NodeSampledTexture {
  19981. constructor( name, textureNode, groupNode, access ) {
  19982. super( name, textureNode, groupNode, access );
  19983. this.isSampledCubeTexture = true;
  19984. }
  19985. }
  19986. class NodeSampledTexture3D extends NodeSampledTexture {
  19987. constructor( name, textureNode, groupNode, access ) {
  19988. super( name, textureNode, groupNode, access );
  19989. this.isSampledTexture3D = true;
  19990. }
  19991. }
  19992. const glslMethods = {
  19993. atan2: 'atan',
  19994. textureDimensions: 'textureSize',
  19995. equals: 'equal'
  19996. };
  19997. const precisionLib = {
  19998. low: 'lowp',
  19999. medium: 'mediump',
  20000. high: 'highp'
  20001. };
  20002. const supports$1 = {
  20003. swizzleAssign: true,
  20004. storageBuffer: false
  20005. };
  20006. const defaultPrecisions = `
  20007. precision highp float;
  20008. precision highp int;
  20009. precision highp sampler2D;
  20010. precision highp sampler3D;
  20011. precision highp samplerCube;
  20012. precision highp sampler2DArray;
  20013. precision highp usampler2D;
  20014. precision highp usampler3D;
  20015. precision highp usamplerCube;
  20016. precision highp usampler2DArray;
  20017. precision highp isampler2D;
  20018. precision highp isampler3D;
  20019. precision highp isamplerCube;
  20020. precision highp isampler2DArray;
  20021. precision lowp sampler2DShadow;
  20022. `;
  20023. class GLSLNodeBuilder extends NodeBuilder {
  20024. constructor( object, renderer ) {
  20025. super( object, renderer, new GLSLNodeParser() );
  20026. this.uniformGroups = {};
  20027. this.transforms = [];
  20028. this.extensions = {};
  20029. this.builtins = { vertex: [], fragment: [], compute: [] };
  20030. this.useComparisonMethod = true;
  20031. }
  20032. needsToWorkingColorSpace( texture ) {
  20033. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  20034. }
  20035. getMethod( method ) {
  20036. return glslMethods[ method ] || method;
  20037. }
  20038. getOutputStructName() {
  20039. return '';
  20040. }
  20041. buildFunctionCode( shaderNode ) {
  20042. const layout = shaderNode.layout;
  20043. const flowData = this.flowShaderNode( shaderNode );
  20044. const parameters = [];
  20045. for ( const input of layout.inputs ) {
  20046. parameters.push( this.getType( input.type ) + ' ' + input.name );
  20047. }
  20048. //
  20049. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  20050. ${ flowData.vars }
  20051. ${ flowData.code }
  20052. return ${ flowData.result };
  20053. }`;
  20054. //
  20055. return code;
  20056. }
  20057. setupPBO( storageBufferNode ) {
  20058. const attribute = storageBufferNode.value;
  20059. if ( attribute.pbo === undefined ) {
  20060. const originalArray = attribute.array;
  20061. const numElements = attribute.count * attribute.itemSize;
  20062. const { itemSize } = attribute;
  20063. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  20064. let format = isInteger ? RedIntegerFormat : RedFormat;
  20065. if ( itemSize === 2 ) {
  20066. format = isInteger ? RGIntegerFormat : RGFormat;
  20067. } else if ( itemSize === 3 ) {
  20068. format = isInteger ? RGBIntegerFormat : RGBFormat;
  20069. } else if ( itemSize === 4 ) {
  20070. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  20071. }
  20072. const typeMap = {
  20073. Float32Array: FloatType,
  20074. Uint8Array: UnsignedByteType,
  20075. Uint16Array: UnsignedShortType,
  20076. Uint32Array: UnsignedIntType,
  20077. Int8Array: ByteType,
  20078. Int16Array: ShortType,
  20079. Int32Array: IntType,
  20080. Uint8ClampedArray: UnsignedByteType,
  20081. };
  20082. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  20083. let height = Math.ceil( ( numElements / itemSize ) / width );
  20084. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  20085. const newSize = width * height * itemSize;
  20086. const newArray = new originalArray.constructor( newSize );
  20087. newArray.set( originalArray, 0 );
  20088. attribute.array = newArray;
  20089. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  20090. pboTexture.needsUpdate = true;
  20091. pboTexture.isPBOTexture = true;
  20092. const pbo = new TextureNode( pboTexture, null, null );
  20093. pbo.setPrecision( 'high' );
  20094. attribute.pboNode = pbo;
  20095. attribute.pbo = pbo.value;
  20096. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  20097. }
  20098. }
  20099. getPropertyName( node, shaderStage = this.shaderStage ) {
  20100. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  20101. return shaderStage.charAt( 0 ) + '_' + node.name;
  20102. }
  20103. return super.getPropertyName( node, shaderStage );
  20104. }
  20105. generatePBO( storageArrayElementNode ) {
  20106. const { node, indexNode } = storageArrayElementNode;
  20107. const attribute = node.value;
  20108. if ( this.renderer.backend.has( attribute ) ) {
  20109. const attributeData = this.renderer.backend.get( attribute );
  20110. attributeData.pbo = attribute.pbo;
  20111. }
  20112. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  20113. const textureName = this.getPropertyName( nodeUniform );
  20114. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  20115. const indexSnippet = indexNode.build( this, 'uint' );
  20116. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  20117. let propertyName = elementNodeData.propertyName;
  20118. if ( propertyName === undefined ) {
  20119. // property element
  20120. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  20121. propertyName = this.getPropertyName( nodeVar );
  20122. // property size
  20123. const bufferNodeData = this.getDataFromNode( node );
  20124. let propertySizeName = bufferNodeData.propertySizeName;
  20125. if ( propertySizeName === undefined ) {
  20126. propertySizeName = propertyName + 'Size';
  20127. this.getVarFromNode( node, propertySizeName, 'uint' );
  20128. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  20129. bufferNodeData.propertySizeName = propertySizeName;
  20130. }
  20131. //
  20132. const { itemSize } = attribute;
  20133. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  20134. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  20135. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  20136. //
  20137. let prefix = 'vec4';
  20138. if ( attribute.pbo.type === UnsignedIntType ) {
  20139. prefix = 'uvec4';
  20140. } else if ( attribute.pbo.type === IntType ) {
  20141. prefix = 'ivec4';
  20142. }
  20143. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  20144. elementNodeData.propertyName = propertyName;
  20145. }
  20146. return propertyName;
  20147. }
  20148. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  20149. if ( depthSnippet ) {
  20150. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  20151. } else {
  20152. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  20153. }
  20154. }
  20155. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  20156. if ( texture.isDepthTexture ) {
  20157. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  20158. } else {
  20159. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  20160. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  20161. }
  20162. }
  20163. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  20164. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  20165. }
  20166. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  20167. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  20168. }
  20169. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  20170. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  20171. }
  20172. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  20173. if ( shaderStage === 'fragment' ) {
  20174. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  20175. } else {
  20176. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  20177. }
  20178. }
  20179. getVars( shaderStage ) {
  20180. const snippets = [];
  20181. const vars = this.vars[ shaderStage ];
  20182. if ( vars !== undefined ) {
  20183. for ( const variable of vars ) {
  20184. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  20185. }
  20186. }
  20187. return snippets.join( '\n\t' );
  20188. }
  20189. getUniforms( shaderStage ) {
  20190. const uniforms = this.uniforms[ shaderStage ];
  20191. const bindingSnippets = [];
  20192. const uniformGroups = {};
  20193. for ( const uniform of uniforms ) {
  20194. let snippet = null;
  20195. let group = false;
  20196. if ( uniform.type === 'texture' ) {
  20197. const texture = uniform.node.value;
  20198. let typePrefix = '';
  20199. if ( texture.isDataTexture === true ) {
  20200. if ( texture.type === UnsignedIntType ) {
  20201. typePrefix = 'u';
  20202. } else if ( texture.type === IntType ) {
  20203. typePrefix = 'i';
  20204. }
  20205. }
  20206. if ( texture.compareFunction ) {
  20207. snippet = `sampler2DShadow ${ uniform.name };`;
  20208. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  20209. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  20210. } else {
  20211. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  20212. }
  20213. } else if ( uniform.type === 'cubeTexture' ) {
  20214. snippet = `samplerCube ${ uniform.name };`;
  20215. } else if ( uniform.type === 'texture3D' ) {
  20216. snippet = `sampler3D ${ uniform.name };`;
  20217. } else if ( uniform.type === 'buffer' ) {
  20218. const bufferNode = uniform.node;
  20219. const bufferType = this.getType( bufferNode.bufferType );
  20220. const bufferCount = bufferNode.bufferCount;
  20221. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  20222. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  20223. } else {
  20224. const vectorType = this.getVectorType( uniform.type );
  20225. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  20226. group = true;
  20227. }
  20228. const precision = uniform.node.precision;
  20229. if ( precision !== null ) {
  20230. snippet = precisionLib[ precision ] + ' ' + snippet;
  20231. }
  20232. if ( group ) {
  20233. snippet = '\t' + snippet;
  20234. const groupName = uniform.groupNode.name;
  20235. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  20236. groupSnippets.push( snippet );
  20237. } else {
  20238. snippet = 'uniform ' + snippet;
  20239. bindingSnippets.push( snippet );
  20240. }
  20241. }
  20242. let output = '';
  20243. for ( const name in uniformGroups ) {
  20244. const groupSnippets = uniformGroups[ name ];
  20245. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  20246. }
  20247. output += bindingSnippets.join( '\n' );
  20248. return output;
  20249. }
  20250. getTypeFromAttribute( attribute ) {
  20251. let nodeType = super.getTypeFromAttribute( attribute );
  20252. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  20253. let dataAttribute = attribute;
  20254. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  20255. const array = dataAttribute.array;
  20256. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  20257. nodeType = nodeType.slice( 1 );
  20258. }
  20259. }
  20260. return nodeType;
  20261. }
  20262. getAttributes( shaderStage ) {
  20263. let snippet = '';
  20264. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  20265. const attributes = this.getAttributesArray();
  20266. let location = 0;
  20267. for ( const attribute of attributes ) {
  20268. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  20269. }
  20270. }
  20271. return snippet;
  20272. }
  20273. getStructMembers( struct ) {
  20274. const snippets = [];
  20275. const members = struct.getMemberTypes();
  20276. for ( let i = 0; i < members.length; i ++ ) {
  20277. const member = members[ i ];
  20278. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  20279. }
  20280. return snippets.join( '\n' );
  20281. }
  20282. getStructs( shaderStage ) {
  20283. const snippets = [];
  20284. const structs = this.structs[ shaderStage ];
  20285. if ( structs.length === 0 ) {
  20286. return 'layout( location = 0 ) out vec4 fragColor;\n';
  20287. }
  20288. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  20289. const struct = structs[ index ];
  20290. let snippet = '\n';
  20291. snippet += this.getStructMembers( struct );
  20292. snippet += '\n';
  20293. snippets.push( snippet );
  20294. }
  20295. return snippets.join( '\n\n' );
  20296. }
  20297. getVaryings( shaderStage ) {
  20298. let snippet = '';
  20299. const varyings = this.varyings;
  20300. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  20301. for ( const varying of varyings ) {
  20302. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  20303. const type = this.getType( varying.type );
  20304. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  20305. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  20306. }
  20307. } else if ( shaderStage === 'fragment' ) {
  20308. for ( const varying of varyings ) {
  20309. if ( varying.needsInterpolation ) {
  20310. const type = this.getType( varying.type );
  20311. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  20312. snippet += `${flat}in ${type} ${varying.name};\n`;
  20313. }
  20314. }
  20315. }
  20316. for ( const builtin of this.builtins[ shaderStage ] ) {
  20317. snippet += `${builtin};\n`;
  20318. }
  20319. return snippet;
  20320. }
  20321. getVertexIndex() {
  20322. return 'uint( gl_VertexID )';
  20323. }
  20324. getInstanceIndex() {
  20325. return 'uint( gl_InstanceID )';
  20326. }
  20327. getInvocationLocalIndex() {
  20328. const workgroupSize = this.object.workgroupSize;
  20329. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  20330. return `uint( gl_InstanceID ) % ${size}u`;
  20331. }
  20332. getDrawIndex() {
  20333. const extensions = this.renderer.backend.extensions;
  20334. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  20335. return 'uint( gl_DrawID )';
  20336. }
  20337. return null;
  20338. }
  20339. getFrontFacing() {
  20340. return 'gl_FrontFacing';
  20341. }
  20342. getFragCoord() {
  20343. return 'gl_FragCoord.xy';
  20344. }
  20345. getFragDepth() {
  20346. return 'gl_FragDepth';
  20347. }
  20348. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  20349. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  20350. if ( map.has( name ) === false ) {
  20351. map.set( name, {
  20352. name,
  20353. behavior
  20354. } );
  20355. }
  20356. }
  20357. getExtensions( shaderStage ) {
  20358. const snippets = [];
  20359. if ( shaderStage === 'vertex' ) {
  20360. const ext = this.renderer.backend.extensions;
  20361. const isBatchedMesh = this.object.isBatchedMesh;
  20362. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  20363. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  20364. }
  20365. }
  20366. const extensions = this.extensions[ shaderStage ];
  20367. if ( extensions !== undefined ) {
  20368. for ( const { name, behavior } of extensions.values() ) {
  20369. snippets.push( `#extension ${name} : ${behavior}` );
  20370. }
  20371. }
  20372. return snippets.join( '\n' );
  20373. }
  20374. getClipDistance() {
  20375. return 'gl_ClipDistance';
  20376. }
  20377. isAvailable( name ) {
  20378. let result = supports$1[ name ];
  20379. if ( result === undefined ) {
  20380. let extensionName;
  20381. result = false;
  20382. switch ( name ) {
  20383. case 'float32Filterable':
  20384. extensionName = 'OES_texture_float_linear';
  20385. break;
  20386. case 'clipDistance':
  20387. extensionName = 'WEBGL_clip_cull_distance';
  20388. break;
  20389. }
  20390. if ( extensionName !== undefined ) {
  20391. const extensions = this.renderer.backend.extensions;
  20392. if ( extensions.has( extensionName ) ) {
  20393. extensions.get( extensionName );
  20394. result = true;
  20395. }
  20396. }
  20397. supports$1[ name ] = result;
  20398. }
  20399. return result;
  20400. }
  20401. isFlipY() {
  20402. return true;
  20403. }
  20404. enableHardwareClipping( planeCount ) {
  20405. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  20406. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  20407. }
  20408. registerTransform( varyingName, attributeNode ) {
  20409. this.transforms.push( { varyingName, attributeNode } );
  20410. }
  20411. getTransforms( /* shaderStage */ ) {
  20412. const transforms = this.transforms;
  20413. let snippet = '';
  20414. for ( let i = 0; i < transforms.length; i ++ ) {
  20415. const transform = transforms[ i ];
  20416. const attributeName = this.getPropertyName( transform.attributeNode );
  20417. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  20418. }
  20419. return snippet;
  20420. }
  20421. _getGLSLUniformStruct( name, vars ) {
  20422. return `
  20423. layout( std140 ) uniform ${name} {
  20424. ${vars}
  20425. };`;
  20426. }
  20427. _getGLSLVertexCode( shaderData ) {
  20428. return `#version 300 es
  20429. ${ this.getSignature() }
  20430. // extensions
  20431. ${shaderData.extensions}
  20432. // precision
  20433. ${ defaultPrecisions }
  20434. // uniforms
  20435. ${shaderData.uniforms}
  20436. // varyings
  20437. ${shaderData.varyings}
  20438. // attributes
  20439. ${shaderData.attributes}
  20440. // codes
  20441. ${shaderData.codes}
  20442. void main() {
  20443. // vars
  20444. ${shaderData.vars}
  20445. // transforms
  20446. ${shaderData.transforms}
  20447. // flow
  20448. ${shaderData.flow}
  20449. gl_PointSize = 1.0;
  20450. }
  20451. `;
  20452. }
  20453. _getGLSLFragmentCode( shaderData ) {
  20454. return `#version 300 es
  20455. ${ this.getSignature() }
  20456. // precision
  20457. ${ defaultPrecisions }
  20458. // uniforms
  20459. ${shaderData.uniforms}
  20460. // varyings
  20461. ${shaderData.varyings}
  20462. // codes
  20463. ${shaderData.codes}
  20464. ${shaderData.structs}
  20465. void main() {
  20466. // vars
  20467. ${shaderData.vars}
  20468. // flow
  20469. ${shaderData.flow}
  20470. }
  20471. `;
  20472. }
  20473. buildCode() {
  20474. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  20475. this.sortBindingGroups();
  20476. for ( const shaderStage in shadersData ) {
  20477. let flow = '// code\n\n';
  20478. flow += this.flowCode[ shaderStage ];
  20479. const flowNodes = this.flowNodes[ shaderStage ];
  20480. const mainNode = flowNodes[ flowNodes.length - 1 ];
  20481. for ( const node of flowNodes ) {
  20482. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  20483. const slotName = node.name;
  20484. if ( slotName ) {
  20485. if ( flow.length > 0 ) flow += '\n';
  20486. flow += `\t// flow -> ${ slotName }\n\t`;
  20487. }
  20488. flow += `${ flowSlotData.code }\n\t`;
  20489. if ( node === mainNode && shaderStage !== 'compute' ) {
  20490. flow += '// result\n\t';
  20491. if ( shaderStage === 'vertex' ) {
  20492. flow += 'gl_Position = ';
  20493. flow += `${ flowSlotData.result };`;
  20494. } else if ( shaderStage === 'fragment' ) {
  20495. if ( ! node.outputNode.isOutputStructNode ) {
  20496. flow += 'fragColor = ';
  20497. flow += `${ flowSlotData.result };`;
  20498. }
  20499. }
  20500. }
  20501. }
  20502. const stageData = shadersData[ shaderStage ];
  20503. stageData.extensions = this.getExtensions( shaderStage );
  20504. stageData.uniforms = this.getUniforms( shaderStage );
  20505. stageData.attributes = this.getAttributes( shaderStage );
  20506. stageData.varyings = this.getVaryings( shaderStage );
  20507. stageData.vars = this.getVars( shaderStage );
  20508. stageData.structs = this.getStructs( shaderStage );
  20509. stageData.codes = this.getCodes( shaderStage );
  20510. stageData.transforms = this.getTransforms( shaderStage );
  20511. stageData.flow = flow;
  20512. }
  20513. if ( this.material !== null ) {
  20514. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  20515. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  20516. } else {
  20517. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  20518. }
  20519. }
  20520. getUniformFromNode( node, type, shaderStage, name = null ) {
  20521. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  20522. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  20523. let uniformGPU = nodeData.uniformGPU;
  20524. if ( uniformGPU === undefined ) {
  20525. const group = node.groupNode;
  20526. const groupName = group.name;
  20527. const bindings = this.getBindGroupArray( groupName, shaderStage );
  20528. if ( type === 'texture' ) {
  20529. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  20530. bindings.push( uniformGPU );
  20531. } else if ( type === 'cubeTexture' ) {
  20532. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  20533. bindings.push( uniformGPU );
  20534. } else if ( type === 'texture3D' ) {
  20535. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  20536. bindings.push( uniformGPU );
  20537. } else if ( type === 'buffer' ) {
  20538. node.name = `NodeBuffer_${ node.id }`;
  20539. uniformNode.name = `buffer${ node.id }`;
  20540. const buffer = new NodeUniformBuffer( node, group );
  20541. buffer.name = node.name;
  20542. bindings.push( buffer );
  20543. uniformGPU = buffer;
  20544. } else {
  20545. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  20546. let uniformsGroup = uniformsStage[ groupName ];
  20547. if ( uniformsGroup === undefined ) {
  20548. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  20549. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  20550. uniformsStage[ groupName ] = uniformsGroup;
  20551. bindings.push( uniformsGroup );
  20552. }
  20553. uniformGPU = this.getNodeUniform( uniformNode, type );
  20554. uniformsGroup.addUniform( uniformGPU );
  20555. }
  20556. nodeData.uniformGPU = uniformGPU;
  20557. }
  20558. return uniformNode;
  20559. }
  20560. }
  20561. let vector2 = null;
  20562. let vector4 = null;
  20563. let color4 = null;
  20564. class Backend {
  20565. constructor( parameters = {} ) {
  20566. this.parameters = Object.assign( {}, parameters );
  20567. this.data = new WeakMap();
  20568. this.renderer = null;
  20569. this.domElement = null;
  20570. }
  20571. async init( renderer ) {
  20572. this.renderer = renderer;
  20573. }
  20574. // render context
  20575. begin( /*renderContext*/ ) { }
  20576. finish( /*renderContext*/ ) { }
  20577. // render object
  20578. draw( /*renderObject, info*/ ) { }
  20579. // program
  20580. createProgram( /*program*/ ) { }
  20581. destroyProgram( /*program*/ ) { }
  20582. // bindings
  20583. createBindings( /*bingGroup, bindings*/ ) { }
  20584. updateBindings( /*bingGroup, bindings*/ ) { }
  20585. // pipeline
  20586. createRenderPipeline( /*renderObject*/ ) { }
  20587. createComputePipeline( /*computeNode, pipeline*/ ) { }
  20588. destroyPipeline( /*pipeline*/ ) { }
  20589. // cache key
  20590. needsRenderUpdate( /*renderObject*/ ) { } // return Boolean ( fast test )
  20591. getRenderCacheKey( /*renderObject*/ ) { } // return String
  20592. // node builder
  20593. createNodeBuilder( /*renderObject*/ ) { } // return NodeBuilder (ADD IT)
  20594. // textures
  20595. createSampler( /*texture*/ ) { }
  20596. createDefaultTexture( /*texture*/ ) { }
  20597. createTexture( /*texture*/ ) { }
  20598. copyTextureToBuffer( /*texture, x, y, width, height*/ ) {}
  20599. // attributes
  20600. createAttribute( /*attribute*/ ) { }
  20601. createIndexAttribute( /*attribute*/ ) { }
  20602. updateAttribute( /*attribute*/ ) { }
  20603. destroyAttribute( /*attribute*/ ) { }
  20604. // canvas
  20605. getContext() { }
  20606. updateSize() { }
  20607. // utils
  20608. resolveTimestampAsync( /*renderContext, type*/ ) { }
  20609. hasFeatureAsync( /*name*/ ) { } // return Boolean
  20610. hasFeature( /*name*/ ) { } // return Boolean
  20611. getInstanceCount( renderObject ) {
  20612. const { object, geometry } = renderObject;
  20613. return geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  20614. }
  20615. getDrawingBufferSize() {
  20616. vector2 = vector2 || new Vector2();
  20617. return this.renderer.getDrawingBufferSize( vector2 );
  20618. }
  20619. getScissor() {
  20620. vector4 = vector4 || new Vector4();
  20621. return this.renderer.getScissor( vector4 );
  20622. }
  20623. setScissorTest( /*boolean*/ ) { }
  20624. getClearColor() {
  20625. const renderer = this.renderer;
  20626. color4 = color4 || new Color4();
  20627. renderer.getClearColor( color4 );
  20628. color4.getRGB( color4, this.renderer.currentColorSpace );
  20629. return color4;
  20630. }
  20631. getDomElement() {
  20632. let domElement = this.domElement;
  20633. if ( domElement === null ) {
  20634. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  20635. // OffscreenCanvas does not have setAttribute, see #22811
  20636. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  20637. this.domElement = domElement;
  20638. }
  20639. return domElement;
  20640. }
  20641. // resource properties
  20642. set( object, value ) {
  20643. this.data.set( object, value );
  20644. }
  20645. get( object ) {
  20646. let map = this.data.get( object );
  20647. if ( map === undefined ) {
  20648. map = {};
  20649. this.data.set( object, map );
  20650. }
  20651. return map;
  20652. }
  20653. has( object ) {
  20654. return this.data.has( object );
  20655. }
  20656. delete( object ) {
  20657. this.data.delete( object );
  20658. }
  20659. dispose() { }
  20660. }
  20661. let _id$1 = 0;
  20662. class DualAttributeData {
  20663. constructor( attributeData, dualBuffer ) {
  20664. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  20665. this.type = attributeData.type;
  20666. this.bufferType = attributeData.bufferType;
  20667. this.pbo = attributeData.pbo;
  20668. this.byteLength = attributeData.byteLength;
  20669. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  20670. this.version = attributeData.version;
  20671. this.isInteger = attributeData.isInteger;
  20672. this.activeBufferIndex = 0;
  20673. this.baseId = attributeData.id;
  20674. }
  20675. get id() {
  20676. return `${ this.baseId }|${ this.activeBufferIndex }`;
  20677. }
  20678. get bufferGPU() {
  20679. return this.buffers[ this.activeBufferIndex ];
  20680. }
  20681. get transformBuffer() {
  20682. return this.buffers[ this.activeBufferIndex ^ 1 ];
  20683. }
  20684. switchBuffers() {
  20685. this.activeBufferIndex ^= 1;
  20686. }
  20687. }
  20688. class WebGLAttributeUtils {
  20689. constructor( backend ) {
  20690. this.backend = backend;
  20691. }
  20692. createAttribute( attribute, bufferType ) {
  20693. const backend = this.backend;
  20694. const { gl } = backend;
  20695. const array = attribute.array;
  20696. const usage = attribute.usage || gl.STATIC_DRAW;
  20697. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  20698. const bufferData = backend.get( bufferAttribute );
  20699. let bufferGPU = bufferData.bufferGPU;
  20700. if ( bufferGPU === undefined ) {
  20701. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  20702. bufferData.bufferGPU = bufferGPU;
  20703. bufferData.bufferType = bufferType;
  20704. bufferData.version = bufferAttribute.version;
  20705. }
  20706. //attribute.onUploadCallback();
  20707. let type;
  20708. if ( array instanceof Float32Array ) {
  20709. type = gl.FLOAT;
  20710. } else if ( array instanceof Uint16Array ) {
  20711. if ( attribute.isFloat16BufferAttribute ) {
  20712. type = gl.HALF_FLOAT;
  20713. } else {
  20714. type = gl.UNSIGNED_SHORT;
  20715. }
  20716. } else if ( array instanceof Int16Array ) {
  20717. type = gl.SHORT;
  20718. } else if ( array instanceof Uint32Array ) {
  20719. type = gl.UNSIGNED_INT;
  20720. } else if ( array instanceof Int32Array ) {
  20721. type = gl.INT;
  20722. } else if ( array instanceof Int8Array ) {
  20723. type = gl.BYTE;
  20724. } else if ( array instanceof Uint8Array ) {
  20725. type = gl.UNSIGNED_BYTE;
  20726. } else if ( array instanceof Uint8ClampedArray ) {
  20727. type = gl.UNSIGNED_BYTE;
  20728. } else {
  20729. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  20730. }
  20731. let attributeData = {
  20732. bufferGPU,
  20733. bufferType,
  20734. type,
  20735. byteLength: array.byteLength,
  20736. bytesPerElement: array.BYTES_PER_ELEMENT,
  20737. version: attribute.version,
  20738. pbo: attribute.pbo,
  20739. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  20740. id: _id$1 ++
  20741. };
  20742. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  20743. // create buffer for tranform feedback use
  20744. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  20745. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  20746. }
  20747. backend.set( attribute, attributeData );
  20748. }
  20749. updateAttribute( attribute ) {
  20750. const backend = this.backend;
  20751. const { gl } = backend;
  20752. const array = attribute.array;
  20753. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  20754. const bufferData = backend.get( bufferAttribute );
  20755. const bufferType = bufferData.bufferType;
  20756. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  20757. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  20758. if ( updateRanges.length === 0 ) {
  20759. // Not using update ranges
  20760. gl.bufferSubData( bufferType, 0, array );
  20761. } else {
  20762. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  20763. const range = updateRanges[ i ];
  20764. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  20765. array, range.start, range.count );
  20766. }
  20767. bufferAttribute.clearUpdateRanges();
  20768. }
  20769. gl.bindBuffer( bufferType, null );
  20770. bufferData.version = bufferAttribute.version;
  20771. }
  20772. destroyAttribute( attribute ) {
  20773. const backend = this.backend;
  20774. const { gl } = backend;
  20775. if ( attribute.isInterleavedBufferAttribute ) {
  20776. backend.delete( attribute.data );
  20777. }
  20778. const attributeData = backend.get( attribute );
  20779. gl.deleteBuffer( attributeData.bufferGPU );
  20780. backend.delete( attribute );
  20781. }
  20782. async getArrayBufferAsync( attribute ) {
  20783. const backend = this.backend;
  20784. const { gl } = backend;
  20785. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  20786. const { bufferGPU } = backend.get( bufferAttribute );
  20787. const array = attribute.array;
  20788. const byteLength = array.byteLength;
  20789. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  20790. const writeBuffer = gl.createBuffer();
  20791. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  20792. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  20793. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  20794. await backend.utils._clientWaitAsync();
  20795. const dstBuffer = new attribute.array.constructor( array.length );
  20796. // Ensure the buffer is bound before reading
  20797. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  20798. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  20799. gl.deleteBuffer( writeBuffer );
  20800. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  20801. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  20802. return dstBuffer.buffer;
  20803. }
  20804. _createBuffer( gl, bufferType, array, usage ) {
  20805. const bufferGPU = gl.createBuffer();
  20806. gl.bindBuffer( bufferType, bufferGPU );
  20807. gl.bufferData( bufferType, array, usage );
  20808. gl.bindBuffer( bufferType, null );
  20809. return bufferGPU;
  20810. }
  20811. }
  20812. let initialized$1 = false, equationToGL, factorToGL;
  20813. class WebGLState {
  20814. constructor( backend ) {
  20815. this.backend = backend;
  20816. this.gl = this.backend.gl;
  20817. this.enabled = {};
  20818. this.currentFlipSided = null;
  20819. this.currentCullFace = null;
  20820. this.currentProgram = null;
  20821. this.currentBlendingEnabled = false;
  20822. this.currentBlending = null;
  20823. this.currentBlendSrc = null;
  20824. this.currentBlendDst = null;
  20825. this.currentBlendSrcAlpha = null;
  20826. this.currentBlendDstAlpha = null;
  20827. this.currentPremultipledAlpha = null;
  20828. this.currentPolygonOffsetFactor = null;
  20829. this.currentPolygonOffsetUnits = null;
  20830. this.currentColorMask = null;
  20831. this.currentDepthFunc = null;
  20832. this.currentDepthMask = null;
  20833. this.currentStencilFunc = null;
  20834. this.currentStencilRef = null;
  20835. this.currentStencilFuncMask = null;
  20836. this.currentStencilFail = null;
  20837. this.currentStencilZFail = null;
  20838. this.currentStencilZPass = null;
  20839. this.currentStencilMask = null;
  20840. this.currentLineWidth = null;
  20841. this.currentClippingPlanes = 0;
  20842. this.currentBoundFramebuffers = {};
  20843. this.currentDrawbuffers = new WeakMap();
  20844. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  20845. this.currentTextureSlot = null;
  20846. this.currentBoundTextures = {};
  20847. this.currentBoundBufferBases = {};
  20848. if ( initialized$1 === false ) {
  20849. this._init( this.gl );
  20850. initialized$1 = true;
  20851. }
  20852. }
  20853. _init( gl ) {
  20854. // Store only WebGL constants here.
  20855. equationToGL = {
  20856. [ AddEquation ]: gl.FUNC_ADD,
  20857. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  20858. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  20859. };
  20860. factorToGL = {
  20861. [ ZeroFactor ]: gl.ZERO,
  20862. [ OneFactor ]: gl.ONE,
  20863. [ SrcColorFactor ]: gl.SRC_COLOR,
  20864. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  20865. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  20866. [ DstColorFactor ]: gl.DST_COLOR,
  20867. [ DstAlphaFactor ]: gl.DST_ALPHA,
  20868. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  20869. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  20870. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  20871. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  20872. };
  20873. }
  20874. enable( id ) {
  20875. const { enabled } = this;
  20876. if ( enabled[ id ] !== true ) {
  20877. this.gl.enable( id );
  20878. enabled[ id ] = true;
  20879. }
  20880. }
  20881. disable( id ) {
  20882. const { enabled } = this;
  20883. if ( enabled[ id ] !== false ) {
  20884. this.gl.disable( id );
  20885. enabled[ id ] = false;
  20886. }
  20887. }
  20888. setFlipSided( flipSided ) {
  20889. if ( this.currentFlipSided !== flipSided ) {
  20890. const { gl } = this;
  20891. if ( flipSided ) {
  20892. gl.frontFace( gl.CW );
  20893. } else {
  20894. gl.frontFace( gl.CCW );
  20895. }
  20896. this.currentFlipSided = flipSided;
  20897. }
  20898. }
  20899. setCullFace( cullFace ) {
  20900. const { gl } = this;
  20901. if ( cullFace !== CullFaceNone ) {
  20902. this.enable( gl.CULL_FACE );
  20903. if ( cullFace !== this.currentCullFace ) {
  20904. if ( cullFace === CullFaceBack ) {
  20905. gl.cullFace( gl.BACK );
  20906. } else if ( cullFace === CullFaceFront ) {
  20907. gl.cullFace( gl.FRONT );
  20908. } else {
  20909. gl.cullFace( gl.FRONT_AND_BACK );
  20910. }
  20911. }
  20912. } else {
  20913. this.disable( gl.CULL_FACE );
  20914. }
  20915. this.currentCullFace = cullFace;
  20916. }
  20917. setLineWidth( width ) {
  20918. const { currentLineWidth, gl } = this;
  20919. if ( width !== currentLineWidth ) {
  20920. gl.lineWidth( width );
  20921. this.currentLineWidth = width;
  20922. }
  20923. }
  20924. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  20925. const { gl } = this;
  20926. if ( blending === NoBlending ) {
  20927. if ( this.currentBlendingEnabled === true ) {
  20928. this.disable( gl.BLEND );
  20929. this.currentBlendingEnabled = false;
  20930. }
  20931. return;
  20932. }
  20933. if ( this.currentBlendingEnabled === false ) {
  20934. this.enable( gl.BLEND );
  20935. this.currentBlendingEnabled = true;
  20936. }
  20937. if ( blending !== CustomBlending ) {
  20938. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  20939. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  20940. gl.blendEquation( gl.FUNC_ADD );
  20941. this.currentBlendEquation = AddEquation;
  20942. this.currentBlendEquationAlpha = AddEquation;
  20943. }
  20944. if ( premultipliedAlpha ) {
  20945. switch ( blending ) {
  20946. case NormalBlending:
  20947. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  20948. break;
  20949. case AdditiveBlending:
  20950. gl.blendFunc( gl.ONE, gl.ONE );
  20951. break;
  20952. case SubtractiveBlending:
  20953. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  20954. break;
  20955. case MultiplyBlending:
  20956. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  20957. break;
  20958. default:
  20959. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  20960. break;
  20961. }
  20962. } else {
  20963. switch ( blending ) {
  20964. case NormalBlending:
  20965. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  20966. break;
  20967. case AdditiveBlending:
  20968. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  20969. break;
  20970. case SubtractiveBlending:
  20971. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  20972. break;
  20973. case MultiplyBlending:
  20974. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  20975. break;
  20976. default:
  20977. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  20978. break;
  20979. }
  20980. }
  20981. this.currentBlendSrc = null;
  20982. this.currentBlendDst = null;
  20983. this.currentBlendSrcAlpha = null;
  20984. this.currentBlendDstAlpha = null;
  20985. this.currentBlending = blending;
  20986. this.currentPremultipledAlpha = premultipliedAlpha;
  20987. }
  20988. return;
  20989. }
  20990. // custom blending
  20991. blendEquationAlpha = blendEquationAlpha || blendEquation;
  20992. blendSrcAlpha = blendSrcAlpha || blendSrc;
  20993. blendDstAlpha = blendDstAlpha || blendDst;
  20994. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  20995. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  20996. this.currentBlendEquation = blendEquation;
  20997. this.currentBlendEquationAlpha = blendEquationAlpha;
  20998. }
  20999. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  21000. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  21001. this.currentBlendSrc = blendSrc;
  21002. this.currentBlendDst = blendDst;
  21003. this.currentBlendSrcAlpha = blendSrcAlpha;
  21004. this.currentBlendDstAlpha = blendDstAlpha;
  21005. }
  21006. this.currentBlending = blending;
  21007. this.currentPremultipledAlpha = false;
  21008. }
  21009. setColorMask( colorMask ) {
  21010. if ( this.currentColorMask !== colorMask ) {
  21011. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  21012. this.currentColorMask = colorMask;
  21013. }
  21014. }
  21015. setDepthTest( depthTest ) {
  21016. const { gl } = this;
  21017. if ( depthTest ) {
  21018. this.enable( gl.DEPTH_TEST );
  21019. } else {
  21020. this.disable( gl.DEPTH_TEST );
  21021. }
  21022. }
  21023. setDepthMask( depthMask ) {
  21024. if ( this.currentDepthMask !== depthMask ) {
  21025. this.gl.depthMask( depthMask );
  21026. this.currentDepthMask = depthMask;
  21027. }
  21028. }
  21029. setDepthFunc( depthFunc ) {
  21030. if ( this.currentDepthFunc !== depthFunc ) {
  21031. const { gl } = this;
  21032. switch ( depthFunc ) {
  21033. case NeverDepth:
  21034. gl.depthFunc( gl.NEVER );
  21035. break;
  21036. case AlwaysDepth:
  21037. gl.depthFunc( gl.ALWAYS );
  21038. break;
  21039. case LessDepth:
  21040. gl.depthFunc( gl.LESS );
  21041. break;
  21042. case LessEqualDepth:
  21043. gl.depthFunc( gl.LEQUAL );
  21044. break;
  21045. case EqualDepth:
  21046. gl.depthFunc( gl.EQUAL );
  21047. break;
  21048. case GreaterEqualDepth:
  21049. gl.depthFunc( gl.GEQUAL );
  21050. break;
  21051. case GreaterDepth:
  21052. gl.depthFunc( gl.GREATER );
  21053. break;
  21054. case NotEqualDepth:
  21055. gl.depthFunc( gl.NOTEQUAL );
  21056. break;
  21057. default:
  21058. gl.depthFunc( gl.LEQUAL );
  21059. }
  21060. this.currentDepthFunc = depthFunc;
  21061. }
  21062. }
  21063. setStencilTest( stencilTest ) {
  21064. const { gl } = this;
  21065. if ( stencilTest ) {
  21066. this.enable( gl.STENCIL_TEST );
  21067. } else {
  21068. this.disable( gl.STENCIL_TEST );
  21069. }
  21070. }
  21071. setStencilMask( stencilMask ) {
  21072. if ( this.currentStencilMask !== stencilMask ) {
  21073. this.gl.stencilMask( stencilMask );
  21074. this.currentStencilMask = stencilMask;
  21075. }
  21076. }
  21077. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  21078. if ( this.currentStencilFunc !== stencilFunc ||
  21079. this.currentStencilRef !== stencilRef ||
  21080. this.currentStencilFuncMask !== stencilMask ) {
  21081. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  21082. this.currentStencilFunc = stencilFunc;
  21083. this.currentStencilRef = stencilRef;
  21084. this.currentStencilFuncMask = stencilMask;
  21085. }
  21086. }
  21087. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  21088. if ( this.currentStencilFail !== stencilFail ||
  21089. this.currentStencilZFail !== stencilZFail ||
  21090. this.currentStencilZPass !== stencilZPass ) {
  21091. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  21092. this.currentStencilFail = stencilFail;
  21093. this.currentStencilZFail = stencilZFail;
  21094. this.currentStencilZPass = stencilZPass;
  21095. }
  21096. }
  21097. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  21098. const { gl } = this;
  21099. material.side === DoubleSide
  21100. ? this.disable( gl.CULL_FACE )
  21101. : this.enable( gl.CULL_FACE );
  21102. let flipSided = ( material.side === BackSide );
  21103. if ( frontFaceCW ) flipSided = ! flipSided;
  21104. this.setFlipSided( flipSided );
  21105. ( material.blending === NormalBlending && material.transparent === false )
  21106. ? this.setBlending( NoBlending )
  21107. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  21108. this.setDepthFunc( material.depthFunc );
  21109. this.setDepthTest( material.depthTest );
  21110. this.setDepthMask( material.depthWrite );
  21111. this.setColorMask( material.colorWrite );
  21112. const stencilWrite = material.stencilWrite;
  21113. this.setStencilTest( stencilWrite );
  21114. if ( stencilWrite ) {
  21115. this.setStencilMask( material.stencilWriteMask );
  21116. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  21117. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  21118. }
  21119. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  21120. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  21121. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  21122. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  21123. if ( hardwareClippingPlanes > 0 ) {
  21124. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  21125. const CLIP_DISTANCE0_WEBGL = 0x3000;
  21126. for ( let i = 0; i < 8; i ++ ) {
  21127. if ( i < hardwareClippingPlanes ) {
  21128. this.enable( CLIP_DISTANCE0_WEBGL + i );
  21129. } else {
  21130. this.disable( CLIP_DISTANCE0_WEBGL + i );
  21131. }
  21132. }
  21133. }
  21134. }
  21135. }
  21136. setPolygonOffset( polygonOffset, factor, units ) {
  21137. const { gl } = this;
  21138. if ( polygonOffset ) {
  21139. this.enable( gl.POLYGON_OFFSET_FILL );
  21140. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  21141. gl.polygonOffset( factor, units );
  21142. this.currentPolygonOffsetFactor = factor;
  21143. this.currentPolygonOffsetUnits = units;
  21144. }
  21145. } else {
  21146. this.disable( gl.POLYGON_OFFSET_FILL );
  21147. }
  21148. }
  21149. useProgram( program ) {
  21150. if ( this.currentProgram !== program ) {
  21151. this.gl.useProgram( program );
  21152. this.currentProgram = program;
  21153. return true;
  21154. }
  21155. return false;
  21156. }
  21157. // framebuffer
  21158. bindFramebuffer( target, framebuffer ) {
  21159. const { gl, currentBoundFramebuffers } = this;
  21160. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  21161. gl.bindFramebuffer( target, framebuffer );
  21162. currentBoundFramebuffers[ target ] = framebuffer;
  21163. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  21164. if ( target === gl.DRAW_FRAMEBUFFER ) {
  21165. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  21166. }
  21167. if ( target === gl.FRAMEBUFFER ) {
  21168. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  21169. }
  21170. return true;
  21171. }
  21172. return false;
  21173. }
  21174. drawBuffers( renderContext, framebuffer ) {
  21175. const { gl } = this;
  21176. let drawBuffers = [];
  21177. let needsUpdate = false;
  21178. if ( renderContext.textures !== null ) {
  21179. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  21180. if ( drawBuffers === undefined ) {
  21181. drawBuffers = [];
  21182. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  21183. }
  21184. const textures = renderContext.textures;
  21185. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  21186. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  21187. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  21188. }
  21189. drawBuffers.length = textures.length;
  21190. needsUpdate = true;
  21191. }
  21192. } else {
  21193. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  21194. drawBuffers[ 0 ] = gl.BACK;
  21195. needsUpdate = true;
  21196. }
  21197. }
  21198. if ( needsUpdate ) {
  21199. gl.drawBuffers( drawBuffers );
  21200. }
  21201. }
  21202. // texture
  21203. activeTexture( webglSlot ) {
  21204. const { gl, currentTextureSlot, maxTextures } = this;
  21205. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  21206. if ( currentTextureSlot !== webglSlot ) {
  21207. gl.activeTexture( webglSlot );
  21208. this.currentTextureSlot = webglSlot;
  21209. }
  21210. }
  21211. bindTexture( webglType, webglTexture, webglSlot ) {
  21212. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  21213. if ( webglSlot === undefined ) {
  21214. if ( currentTextureSlot === null ) {
  21215. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  21216. } else {
  21217. webglSlot = currentTextureSlot;
  21218. }
  21219. }
  21220. let boundTexture = currentBoundTextures[ webglSlot ];
  21221. if ( boundTexture === undefined ) {
  21222. boundTexture = { type: undefined, texture: undefined };
  21223. currentBoundTextures[ webglSlot ] = boundTexture;
  21224. }
  21225. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  21226. if ( currentTextureSlot !== webglSlot ) {
  21227. gl.activeTexture( webglSlot );
  21228. this.currentTextureSlot = webglSlot;
  21229. }
  21230. gl.bindTexture( webglType, webglTexture );
  21231. boundTexture.type = webglType;
  21232. boundTexture.texture = webglTexture;
  21233. }
  21234. }
  21235. bindBufferBase( target, index, buffer ) {
  21236. const { gl } = this;
  21237. const key = `${target}-${index}`;
  21238. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  21239. gl.bindBufferBase( target, index, buffer );
  21240. this.currentBoundBufferBases[ key ] = buffer;
  21241. return true;
  21242. }
  21243. return false;
  21244. }
  21245. unbindTexture() {
  21246. const { gl, currentTextureSlot, currentBoundTextures } = this;
  21247. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  21248. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  21249. gl.bindTexture( boundTexture.type, null );
  21250. boundTexture.type = undefined;
  21251. boundTexture.texture = undefined;
  21252. }
  21253. }
  21254. }
  21255. class WebGLUtils {
  21256. constructor( backend ) {
  21257. this.backend = backend;
  21258. this.gl = this.backend.gl;
  21259. this.extensions = backend.extensions;
  21260. }
  21261. convert( p, colorSpace = NoColorSpace ) {
  21262. const { gl, extensions } = this;
  21263. let extension;
  21264. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  21265. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  21266. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  21267. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  21268. if ( p === ByteType ) return gl.BYTE;
  21269. if ( p === ShortType ) return gl.SHORT;
  21270. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  21271. if ( p === IntType ) return gl.INT;
  21272. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  21273. if ( p === FloatType ) return gl.FLOAT;
  21274. if ( p === HalfFloatType ) {
  21275. return gl.HALF_FLOAT;
  21276. }
  21277. if ( p === AlphaFormat ) return gl.ALPHA;
  21278. if ( p === RGBFormat ) return gl.RGB;
  21279. if ( p === RGBAFormat ) return gl.RGBA;
  21280. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  21281. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  21282. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  21283. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  21284. // WebGL2 formats.
  21285. if ( p === RedFormat ) return gl.RED;
  21286. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  21287. if ( p === RGFormat ) return gl.RG;
  21288. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  21289. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  21290. // S3TC
  21291. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  21292. if ( colorSpace === SRGBColorSpace ) {
  21293. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  21294. if ( extension !== null ) {
  21295. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  21296. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  21297. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  21298. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  21299. } else {
  21300. return null;
  21301. }
  21302. } else {
  21303. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  21304. if ( extension !== null ) {
  21305. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  21306. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  21307. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  21308. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  21309. } else {
  21310. return null;
  21311. }
  21312. }
  21313. }
  21314. // PVRTC
  21315. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  21316. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  21317. if ( extension !== null ) {
  21318. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  21319. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  21320. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  21321. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  21322. } else {
  21323. return null;
  21324. }
  21325. }
  21326. // ETC
  21327. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  21328. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  21329. if ( extension !== null ) {
  21330. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  21331. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  21332. } else {
  21333. return null;
  21334. }
  21335. }
  21336. // ASTC
  21337. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  21338. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  21339. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  21340. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  21341. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  21342. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  21343. if ( extension !== null ) {
  21344. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  21345. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  21346. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  21347. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  21348. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  21349. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  21350. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  21351. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  21352. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  21353. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  21354. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  21355. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  21356. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  21357. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  21358. } else {
  21359. return null;
  21360. }
  21361. }
  21362. // BPTC
  21363. if ( p === RGBA_BPTC_Format ) {
  21364. extension = extensions.get( 'EXT_texture_compression_bptc' );
  21365. if ( extension !== null ) {
  21366. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  21367. } else {
  21368. return null;
  21369. }
  21370. }
  21371. // RGTC
  21372. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  21373. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  21374. if ( extension !== null ) {
  21375. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  21376. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  21377. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  21378. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  21379. } else {
  21380. return null;
  21381. }
  21382. }
  21383. //
  21384. if ( p === UnsignedInt248Type ) {
  21385. return gl.UNSIGNED_INT_24_8;
  21386. }
  21387. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  21388. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  21389. }
  21390. _clientWaitAsync() {
  21391. const { gl } = this;
  21392. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  21393. gl.flush();
  21394. return new Promise( ( resolve, reject ) => {
  21395. function test() {
  21396. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  21397. if ( res === gl.WAIT_FAILED ) {
  21398. gl.deleteSync( sync );
  21399. reject();
  21400. return;
  21401. }
  21402. if ( res === gl.TIMEOUT_EXPIRED ) {
  21403. requestAnimationFrame( test );
  21404. return;
  21405. }
  21406. gl.deleteSync( sync );
  21407. resolve();
  21408. }
  21409. test();
  21410. } );
  21411. }
  21412. }
  21413. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  21414. class WebGLTextureUtils {
  21415. constructor( backend ) {
  21416. this.backend = backend;
  21417. this.gl = backend.gl;
  21418. this.extensions = backend.extensions;
  21419. this.defaultTextures = {};
  21420. if ( initialized === false ) {
  21421. this._init( this.gl );
  21422. initialized = true;
  21423. }
  21424. }
  21425. _init( gl ) {
  21426. // Store only WebGL constants here.
  21427. wrappingToGL = {
  21428. [ RepeatWrapping ]: gl.REPEAT,
  21429. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  21430. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  21431. };
  21432. filterToGL = {
  21433. [ NearestFilter ]: gl.NEAREST,
  21434. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  21435. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  21436. [ LinearFilter ]: gl.LINEAR,
  21437. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  21438. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  21439. };
  21440. compareToGL = {
  21441. [ NeverCompare ]: gl.NEVER,
  21442. [ AlwaysCompare ]: gl.ALWAYS,
  21443. [ LessCompare ]: gl.LESS,
  21444. [ LessEqualCompare ]: gl.LEQUAL,
  21445. [ EqualCompare ]: gl.EQUAL,
  21446. [ GreaterEqualCompare ]: gl.GEQUAL,
  21447. [ GreaterCompare ]: gl.GREATER,
  21448. [ NotEqualCompare ]: gl.NOTEQUAL
  21449. };
  21450. }
  21451. filterFallback( f ) {
  21452. const { gl } = this;
  21453. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  21454. return gl.NEAREST;
  21455. }
  21456. return gl.LINEAR;
  21457. }
  21458. getGLTextureType( texture ) {
  21459. const { gl } = this;
  21460. let glTextureType;
  21461. if ( texture.isCubeTexture === true ) {
  21462. glTextureType = gl.TEXTURE_CUBE_MAP;
  21463. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  21464. glTextureType = gl.TEXTURE_2D_ARRAY;
  21465. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  21466. glTextureType = gl.TEXTURE_3D;
  21467. } else {
  21468. glTextureType = gl.TEXTURE_2D;
  21469. }
  21470. return glTextureType;
  21471. }
  21472. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  21473. const { gl, extensions } = this;
  21474. if ( internalFormatName !== null ) {
  21475. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  21476. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  21477. }
  21478. let internalFormat = glFormat;
  21479. if ( glFormat === gl.RED ) {
  21480. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  21481. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  21482. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  21483. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  21484. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  21485. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  21486. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  21487. if ( glType === gl.INT ) internalFormat = gl.R32I;
  21488. }
  21489. if ( glFormat === gl.RED_INTEGER ) {
  21490. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  21491. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  21492. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  21493. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  21494. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  21495. if ( glType === gl.INT ) internalFormat = gl.R32I;
  21496. }
  21497. if ( glFormat === gl.RG ) {
  21498. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  21499. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  21500. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  21501. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  21502. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  21503. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  21504. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  21505. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  21506. }
  21507. if ( glFormat === gl.RG_INTEGER ) {
  21508. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  21509. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  21510. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  21511. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  21512. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  21513. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  21514. }
  21515. if ( glFormat === gl.RGB ) {
  21516. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  21517. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  21518. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  21519. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  21520. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  21521. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  21522. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  21523. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  21524. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  21525. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  21526. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  21527. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  21528. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  21529. }
  21530. if ( glFormat === gl.RGB_INTEGER ) {
  21531. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  21532. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  21533. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  21534. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  21535. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  21536. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  21537. }
  21538. if ( glFormat === gl.RGBA ) {
  21539. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  21540. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  21541. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  21542. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  21543. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  21544. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  21545. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  21546. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  21547. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  21548. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  21549. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  21550. }
  21551. if ( glFormat === gl.RGBA_INTEGER ) {
  21552. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  21553. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  21554. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  21555. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  21556. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  21557. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  21558. }
  21559. if ( glFormat === gl.DEPTH_COMPONENT ) {
  21560. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  21561. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  21562. }
  21563. if ( glFormat === gl.DEPTH_STENCIL ) {
  21564. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  21565. }
  21566. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  21567. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  21568. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  21569. extensions.get( 'EXT_color_buffer_float' );
  21570. }
  21571. return internalFormat;
  21572. }
  21573. setTextureParameters( textureType, texture ) {
  21574. const { gl, extensions, backend } = this;
  21575. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  21576. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  21577. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  21578. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  21579. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  21580. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  21581. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  21582. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  21583. }
  21584. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  21585. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  21586. // follow WebGPU backend mapping for texture filtering
  21587. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  21588. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  21589. if ( texture.compareFunction ) {
  21590. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  21591. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  21592. }
  21593. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  21594. if ( texture.magFilter === NearestFilter ) return;
  21595. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  21596. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  21597. if ( texture.anisotropy > 1 ) {
  21598. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  21599. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  21600. }
  21601. }
  21602. }
  21603. createDefaultTexture( texture ) {
  21604. const { gl, backend, defaultTextures } = this;
  21605. const glTextureType = this.getGLTextureType( texture );
  21606. let textureGPU = defaultTextures[ glTextureType ];
  21607. if ( textureGPU === undefined ) {
  21608. textureGPU = gl.createTexture();
  21609. backend.state.bindTexture( glTextureType, textureGPU );
  21610. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  21611. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  21612. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  21613. defaultTextures[ glTextureType ] = textureGPU;
  21614. }
  21615. backend.set( texture, {
  21616. textureGPU,
  21617. glTextureType,
  21618. isDefault: true
  21619. } );
  21620. }
  21621. createTexture( texture, options ) {
  21622. const { gl, backend } = this;
  21623. const { levels, width, height, depth } = options;
  21624. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  21625. const glType = backend.utils.convert( texture.type );
  21626. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  21627. const textureGPU = gl.createTexture();
  21628. const glTextureType = this.getGLTextureType( texture );
  21629. backend.state.bindTexture( glTextureType, textureGPU );
  21630. this.setTextureParameters( glTextureType, texture );
  21631. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  21632. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  21633. } else if ( texture.isData3DTexture ) {
  21634. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  21635. } else if ( ! texture.isVideoTexture ) {
  21636. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  21637. }
  21638. backend.set( texture, {
  21639. textureGPU,
  21640. glTextureType,
  21641. glFormat,
  21642. glType,
  21643. glInternalFormat
  21644. } );
  21645. }
  21646. copyBufferToTexture( buffer, texture ) {
  21647. const { gl, backend } = this;
  21648. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  21649. const { width, height } = texture.source.data;
  21650. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  21651. backend.state.bindTexture( glTextureType, textureGPU );
  21652. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  21653. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  21654. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  21655. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  21656. backend.state.unbindTexture();
  21657. // debug
  21658. // const framebuffer = gl.createFramebuffer();
  21659. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  21660. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  21661. // const readout = new Float32Array( width * height * 4 );
  21662. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  21663. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  21664. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  21665. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  21666. // console.log( readout );
  21667. }
  21668. updateTexture( texture, options ) {
  21669. const { gl } = this;
  21670. const { width, height } = options;
  21671. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  21672. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  21673. return;
  21674. const getImage = ( source ) => {
  21675. if ( source.isDataTexture ) {
  21676. return source.image.data;
  21677. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  21678. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  21679. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  21680. source instanceof OffscreenCanvas ) {
  21681. return source;
  21682. }
  21683. return source.data;
  21684. };
  21685. this.backend.state.bindTexture( glTextureType, textureGPU );
  21686. this.setTextureParameters( glTextureType, texture );
  21687. if ( texture.isCompressedTexture ) {
  21688. const mipmaps = texture.mipmaps;
  21689. const image = options.image;
  21690. for ( let i = 0; i < mipmaps.length; i ++ ) {
  21691. const mipmap = mipmaps[ i ];
  21692. if ( texture.isCompressedArrayTexture ) {
  21693. if ( texture.format !== gl.RGBA ) {
  21694. if ( glFormat !== null ) {
  21695. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  21696. } else {
  21697. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  21698. }
  21699. } else {
  21700. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  21701. }
  21702. } else {
  21703. if ( glFormat !== null ) {
  21704. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  21705. } else {
  21706. console.warn( 'Unsupported compressed texture format' );
  21707. }
  21708. }
  21709. }
  21710. } else if ( texture.isCubeTexture ) {
  21711. const images = options.images;
  21712. for ( let i = 0; i < 6; i ++ ) {
  21713. const image = getImage( images[ i ] );
  21714. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  21715. }
  21716. } else if ( texture.isDataArrayTexture ) {
  21717. const image = options.image;
  21718. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  21719. } else if ( texture.isData3DTexture ) {
  21720. const image = options.image;
  21721. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  21722. } else if ( texture.isVideoTexture ) {
  21723. texture.update();
  21724. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  21725. } else {
  21726. const image = getImage( options.image );
  21727. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  21728. }
  21729. }
  21730. generateMipmaps( texture ) {
  21731. const { gl, backend } = this;
  21732. const { textureGPU, glTextureType } = backend.get( texture );
  21733. backend.state.bindTexture( glTextureType, textureGPU );
  21734. gl.generateMipmap( glTextureType );
  21735. }
  21736. deallocateRenderBuffers( renderTarget ) {
  21737. const { gl, backend } = this;
  21738. // remove framebuffer reference
  21739. if ( renderTarget ) {
  21740. const renderContextData = backend.get( renderTarget );
  21741. renderContextData.renderBufferStorageSetup = undefined;
  21742. if ( renderContextData.framebuffers ) {
  21743. for ( const cacheKey in renderContextData.framebuffers ) {
  21744. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  21745. }
  21746. delete renderContextData.framebuffers;
  21747. }
  21748. if ( renderContextData.depthRenderbuffer ) {
  21749. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  21750. delete renderContextData.depthRenderbuffer;
  21751. }
  21752. if ( renderContextData.stencilRenderbuffer ) {
  21753. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  21754. delete renderContextData.stencilRenderbuffer;
  21755. }
  21756. if ( renderContextData.msaaFrameBuffer ) {
  21757. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  21758. delete renderContextData.msaaFrameBuffer;
  21759. }
  21760. if ( renderContextData.msaaRenderbuffers ) {
  21761. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  21762. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  21763. }
  21764. delete renderContextData.msaaRenderbuffers;
  21765. }
  21766. }
  21767. }
  21768. destroyTexture( texture ) {
  21769. const { gl, backend } = this;
  21770. const { textureGPU, renderTarget } = backend.get( texture );
  21771. this.deallocateRenderBuffers( renderTarget );
  21772. gl.deleteTexture( textureGPU );
  21773. backend.delete( texture );
  21774. }
  21775. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  21776. const { gl, backend } = this;
  21777. const { state } = this.backend;
  21778. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  21779. let width, height, minX, minY;
  21780. let dstX, dstY;
  21781. if ( srcRegion !== null ) {
  21782. width = srcRegion.max.x - srcRegion.min.x;
  21783. height = srcRegion.max.y - srcRegion.min.y;
  21784. minX = srcRegion.min.x;
  21785. minY = srcRegion.min.y;
  21786. } else {
  21787. width = srcTexture.image.width;
  21788. height = srcTexture.image.height;
  21789. minX = 0;
  21790. minY = 0;
  21791. }
  21792. if ( dstPosition !== null ) {
  21793. dstX = dstPosition.x;
  21794. dstY = dstPosition.y;
  21795. } else {
  21796. dstX = 0;
  21797. dstY = 0;
  21798. }
  21799. state.bindTexture( glTextureType, dstTextureGPU );
  21800. // As another texture upload may have changed pixelStorei
  21801. // parameters, make sure they are correct for the dstTexture
  21802. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  21803. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  21804. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  21805. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  21806. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  21807. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  21808. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  21809. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  21810. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  21811. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  21812. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  21813. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  21814. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  21815. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  21816. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  21817. const srcTextureData = backend.get( srcTexture );
  21818. const dstTextureData = backend.get( dstTexture );
  21819. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  21820. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  21821. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  21822. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  21823. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  21824. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  21825. let mask = gl.COLOR_BUFFER_BIT;
  21826. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  21827. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  21828. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  21829. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  21830. } else {
  21831. if ( srcTexture.isDataTexture ) {
  21832. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  21833. } else {
  21834. if ( srcTexture.isCompressedTexture ) {
  21835. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  21836. } else {
  21837. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  21838. }
  21839. }
  21840. }
  21841. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  21842. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  21843. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  21844. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  21845. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  21846. // Generate mipmaps only when copying level 0
  21847. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  21848. state.unbindTexture();
  21849. }
  21850. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  21851. const { gl } = this;
  21852. const { state } = this.backend;
  21853. const { textureGPU } = this.backend.get( texture );
  21854. const { x, y, z: width, w: height } = rectangle;
  21855. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  21856. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.gerDrawingBufferSize().y;
  21857. if ( requireDrawFrameBuffer ) {
  21858. const partial = ( x !== 0 || y !== 0 );
  21859. let mask;
  21860. let attachment;
  21861. if ( texture.isDepthTexture === true ) {
  21862. mask = gl.DEPTH_BUFFER_BIT;
  21863. attachment = gl.DEPTH_ATTACHMENT;
  21864. if ( renderContext.stencil ) {
  21865. mask |= gl.STENCIL_BUFFER_BIT;
  21866. }
  21867. } else {
  21868. mask = gl.COLOR_BUFFER_BIT;
  21869. attachment = gl.COLOR_ATTACHMENT0;
  21870. }
  21871. if ( partial ) {
  21872. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  21873. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  21874. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  21875. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  21876. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  21877. const flippedY = srcHeight - y - height;
  21878. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  21879. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  21880. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  21881. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  21882. state.unbindTexture();
  21883. } else {
  21884. const fb = gl.createFramebuffer();
  21885. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  21886. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  21887. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  21888. gl.deleteFramebuffer( fb );
  21889. }
  21890. } else {
  21891. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  21892. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  21893. state.unbindTexture();
  21894. }
  21895. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  21896. this.backend._setFramebuffer( renderContext );
  21897. }
  21898. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  21899. setupRenderBufferStorage( renderbuffer, renderContext ) {
  21900. const { gl } = this;
  21901. const renderTarget = renderContext.renderTarget;
  21902. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  21903. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  21904. if ( depthBuffer && ! stencilBuffer ) {
  21905. let glInternalFormat = gl.DEPTH_COMPONENT24;
  21906. if ( samples > 0 ) {
  21907. if ( depthTexture && depthTexture.isDepthTexture ) {
  21908. if ( depthTexture.type === gl.FLOAT ) {
  21909. glInternalFormat = gl.DEPTH_COMPONENT32F;
  21910. }
  21911. }
  21912. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  21913. } else {
  21914. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  21915. }
  21916. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  21917. } else if ( depthBuffer && stencilBuffer ) {
  21918. if ( samples > 0 ) {
  21919. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  21920. } else {
  21921. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  21922. }
  21923. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  21924. }
  21925. }
  21926. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  21927. const { backend, gl } = this;
  21928. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  21929. const fb = gl.createFramebuffer();
  21930. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  21931. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  21932. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  21933. const typedArrayType = this._getTypedArrayType( glType );
  21934. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  21935. const elementCount = width * height;
  21936. const byteLength = elementCount * bytesPerTexel;
  21937. const buffer = gl.createBuffer();
  21938. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  21939. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  21940. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  21941. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  21942. await backend.utils._clientWaitAsync();
  21943. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  21944. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  21945. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  21946. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  21947. gl.deleteFramebuffer( fb );
  21948. return dstBuffer;
  21949. }
  21950. _getTypedArrayType( glType ) {
  21951. const { gl } = this;
  21952. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  21953. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  21954. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  21955. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  21956. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  21957. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  21958. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  21959. if ( glType === gl.FLOAT ) return Float32Array;
  21960. throw new Error( `Unsupported WebGL type: ${glType}` );
  21961. }
  21962. _getBytesPerTexel( glType, glFormat ) {
  21963. const { gl } = this;
  21964. let bytesPerComponent = 0;
  21965. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  21966. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  21967. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  21968. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  21969. glType === gl.UNSIGNED_SHORT ||
  21970. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  21971. if ( glType === gl.UNSIGNED_INT ||
  21972. glType === gl.FLOAT ) bytesPerComponent = 4;
  21973. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  21974. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  21975. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  21976. }
  21977. }
  21978. class WebGLExtensions {
  21979. constructor( backend ) {
  21980. this.backend = backend;
  21981. this.gl = this.backend.gl;
  21982. this.availableExtensions = this.gl.getSupportedExtensions();
  21983. this.extensions = {};
  21984. }
  21985. get( name ) {
  21986. let extension = this.extensions[ name ];
  21987. if ( extension === undefined ) {
  21988. extension = this.gl.getExtension( name );
  21989. this.extensions[ name ] = extension;
  21990. }
  21991. return extension;
  21992. }
  21993. has( name ) {
  21994. return this.availableExtensions.includes( name );
  21995. }
  21996. }
  21997. class WebGLCapabilities {
  21998. constructor( backend ) {
  21999. this.backend = backend;
  22000. this.maxAnisotropy = null;
  22001. }
  22002. getMaxAnisotropy() {
  22003. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  22004. const gl = this.backend.gl;
  22005. const extensions = this.backend.extensions;
  22006. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  22007. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  22008. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  22009. } else {
  22010. this.maxAnisotropy = 0;
  22011. }
  22012. return this.maxAnisotropy;
  22013. }
  22014. }
  22015. const GLFeatureName = {
  22016. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  22017. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  22018. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  22019. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  22020. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  22021. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  22022. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  22023. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  22024. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  22025. };
  22026. class WebGLBufferRenderer {
  22027. constructor( backend ) {
  22028. this.gl = backend.gl;
  22029. this.extensions = backend.extensions;
  22030. this.info = backend.renderer.info;
  22031. this.mode = null;
  22032. this.index = 0;
  22033. this.type = null;
  22034. this.object = null;
  22035. }
  22036. render( start, count ) {
  22037. const { gl, mode, object, type, info, index } = this;
  22038. if ( index !== 0 ) {
  22039. gl.drawElements( mode, count, type, start );
  22040. } else {
  22041. gl.drawArrays( mode, start, count );
  22042. }
  22043. info.update( object, count, mode, 1 );
  22044. }
  22045. renderInstances( start, count, primcount ) {
  22046. const { gl, mode, type, index, object, info } = this;
  22047. if ( primcount === 0 ) return;
  22048. if ( index !== 0 ) {
  22049. gl.drawElementsInstanced( mode, count, type, start, primcount );
  22050. } else {
  22051. gl.drawArraysInstanced( mode, start, count, primcount );
  22052. }
  22053. info.update( object, count, mode, primcount );
  22054. }
  22055. renderMultiDraw( starts, counts, drawCount ) {
  22056. const { extensions, mode, object, info } = this;
  22057. if ( drawCount === 0 ) return;
  22058. const extension = extensions.get( 'WEBGL_multi_draw' );
  22059. if ( extension === null ) {
  22060. for ( let i = 0; i < drawCount; i ++ ) {
  22061. this.render( starts[ i ], counts[ i ] );
  22062. }
  22063. } else {
  22064. if ( this.index !== 0 ) {
  22065. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  22066. } else {
  22067. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  22068. }
  22069. let elementCount = 0;
  22070. for ( let i = 0; i < drawCount; i ++ ) {
  22071. elementCount += counts[ i ];
  22072. }
  22073. info.update( object, elementCount, mode, 1 );
  22074. }
  22075. }
  22076. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  22077. const { extensions, mode, object, info } = this;
  22078. if ( drawCount === 0 ) return;
  22079. const extension = extensions.get( 'WEBGL_multi_draw' );
  22080. if ( extension === null ) {
  22081. for ( let i = 0; i < drawCount; i ++ ) {
  22082. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  22083. }
  22084. } else {
  22085. if ( this.index !== 0 ) {
  22086. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  22087. } else {
  22088. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  22089. }
  22090. let elementCount = 0;
  22091. for ( let i = 0; i < drawCount; i ++ ) {
  22092. elementCount += counts[ i ] * primcount[ i ];
  22093. }
  22094. info.update( object, elementCount, mode, 1 );
  22095. }
  22096. }
  22097. //
  22098. }
  22099. //
  22100. class WebGLBackend extends Backend {
  22101. constructor( parameters = {} ) {
  22102. super( parameters );
  22103. this.isWebGLBackend = true;
  22104. }
  22105. init( renderer ) {
  22106. super.init( renderer );
  22107. //
  22108. const parameters = this.parameters;
  22109. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  22110. function onContextLost( event ) {
  22111. event.preventDefault();
  22112. const contextLossInfo = {
  22113. api: 'WebGL',
  22114. message: event.statusMessage || 'Unknown reason',
  22115. reason: null,
  22116. originalEvent: event
  22117. };
  22118. renderer.onDeviceLost( contextLossInfo );
  22119. }
  22120. this._onContextLost = onContextLost;
  22121. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  22122. this.gl = glContext;
  22123. this.extensions = new WebGLExtensions( this );
  22124. this.capabilities = new WebGLCapabilities( this );
  22125. this.attributeUtils = new WebGLAttributeUtils( this );
  22126. this.textureUtils = new WebGLTextureUtils( this );
  22127. this.bufferRenderer = new WebGLBufferRenderer( this );
  22128. this.state = new WebGLState( this );
  22129. this.utils = new WebGLUtils( this );
  22130. this.vaoCache = {};
  22131. this.transformFeedbackCache = {};
  22132. this.discard = false;
  22133. this.trackTimestamp = ( parameters.trackTimestamp === true );
  22134. this.extensions.get( 'EXT_color_buffer_float' );
  22135. this.extensions.get( 'WEBGL_clip_cull_distance' );
  22136. this.extensions.get( 'OES_texture_float_linear' );
  22137. this.extensions.get( 'EXT_color_buffer_half_float' );
  22138. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  22139. this.extensions.get( 'WEBGL_render_shared_exponent' );
  22140. this.extensions.get( 'WEBGL_multi_draw' );
  22141. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  22142. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  22143. this._knownBindings = new WeakSet();
  22144. this._currentContext = null;
  22145. }
  22146. get coordinateSystem() {
  22147. return WebGLCoordinateSystem;
  22148. }
  22149. async getArrayBufferAsync( attribute ) {
  22150. return await this.attributeUtils.getArrayBufferAsync( attribute );
  22151. }
  22152. async waitForGPU() {
  22153. await this.utils._clientWaitAsync();
  22154. }
  22155. initTimestampQuery( renderContext ) {
  22156. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  22157. const renderContextData = this.get( renderContext );
  22158. if ( this.queryRunning ) {
  22159. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  22160. renderContextData.queryQueue.push( renderContext );
  22161. return;
  22162. }
  22163. if ( renderContextData.activeQuery ) {
  22164. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  22165. renderContextData.activeQuery = null;
  22166. }
  22167. renderContextData.activeQuery = this.gl.createQuery();
  22168. if ( renderContextData.activeQuery !== null ) {
  22169. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  22170. this.queryRunning = true;
  22171. }
  22172. }
  22173. // timestamp utils
  22174. prepareTimestampBuffer( renderContext ) {
  22175. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  22176. const renderContextData = this.get( renderContext );
  22177. if ( renderContextData.activeQuery ) {
  22178. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  22179. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  22180. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  22181. renderContextData.activeQuery = null;
  22182. this.queryRunning = false;
  22183. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  22184. const nextRenderContext = renderContextData.queryQueue.shift();
  22185. this.initTimestampQuery( nextRenderContext );
  22186. }
  22187. }
  22188. }
  22189. async resolveTimestampAsync( renderContext, type = 'render' ) {
  22190. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  22191. const renderContextData = this.get( renderContext );
  22192. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  22193. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  22194. const queryInfo = renderContextData.gpuQueries[ i ];
  22195. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  22196. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  22197. if ( available && ! disjoint ) {
  22198. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  22199. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  22200. this.gl.deleteQuery( queryInfo.query );
  22201. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  22202. i --;
  22203. this.renderer.info.updateTimestamp( type, duration );
  22204. }
  22205. }
  22206. }
  22207. getContext() {
  22208. return this.gl;
  22209. }
  22210. beginRender( renderContext ) {
  22211. const { gl } = this;
  22212. const renderContextData = this.get( renderContext );
  22213. //
  22214. //
  22215. this.initTimestampQuery( renderContext );
  22216. renderContextData.previousContext = this._currentContext;
  22217. this._currentContext = renderContext;
  22218. this._setFramebuffer( renderContext );
  22219. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  22220. //
  22221. if ( renderContext.viewport ) {
  22222. this.updateViewport( renderContext );
  22223. } else {
  22224. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  22225. }
  22226. if ( renderContext.scissor ) {
  22227. const { x, y, width, height } = renderContext.scissorValue;
  22228. gl.scissor( x, renderContext.height - height - y, width, height );
  22229. }
  22230. const occlusionQueryCount = renderContext.occlusionQueryCount;
  22231. if ( occlusionQueryCount > 0 ) {
  22232. // Get a reference to the array of objects with queries. The renderContextData property
  22233. // can be changed by another render pass before the async reading of all previous queries complete
  22234. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  22235. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  22236. renderContextData.lastOcclusionObject = null;
  22237. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  22238. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  22239. renderContextData.occlusionQueryIndex = 0;
  22240. }
  22241. }
  22242. finishRender( renderContext ) {
  22243. const { gl, state } = this;
  22244. const renderContextData = this.get( renderContext );
  22245. const previousContext = renderContextData.previousContext;
  22246. const occlusionQueryCount = renderContext.occlusionQueryCount;
  22247. if ( occlusionQueryCount > 0 ) {
  22248. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  22249. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  22250. }
  22251. this.resolveOccludedAsync( renderContext );
  22252. }
  22253. const textures = renderContext.textures;
  22254. if ( textures !== null ) {
  22255. for ( let i = 0; i < textures.length; i ++ ) {
  22256. const texture = textures[ i ];
  22257. if ( texture.generateMipmaps ) {
  22258. this.generateMipmaps( texture );
  22259. }
  22260. }
  22261. }
  22262. this._currentContext = previousContext;
  22263. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  22264. const renderTargetContextData = this.get( renderContext.renderTarget );
  22265. const { samples } = renderContext.renderTarget;
  22266. if ( samples > 0 ) {
  22267. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  22268. const mask = gl.COLOR_BUFFER_BIT;
  22269. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  22270. const textures = renderContext.textures;
  22271. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  22272. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  22273. for ( let i = 0; i < textures.length; i ++ ) {
  22274. // TODO Add support for MRT
  22275. if ( renderContext.scissor ) {
  22276. const { x, y, width, height } = renderContext.scissorValue;
  22277. const viewY = renderContext.height - height - y;
  22278. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  22279. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  22280. } else {
  22281. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  22282. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  22283. }
  22284. }
  22285. }
  22286. }
  22287. if ( previousContext !== null ) {
  22288. this._setFramebuffer( previousContext );
  22289. if ( previousContext.viewport ) {
  22290. this.updateViewport( previousContext );
  22291. } else {
  22292. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  22293. }
  22294. }
  22295. this.prepareTimestampBuffer( renderContext );
  22296. }
  22297. resolveOccludedAsync( renderContext ) {
  22298. const renderContextData = this.get( renderContext );
  22299. // handle occlusion query results
  22300. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  22301. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  22302. const occluded = new WeakSet();
  22303. const { gl } = this;
  22304. renderContextData.currentOcclusionQueryObjects = null;
  22305. renderContextData.currentOcclusionQueries = null;
  22306. const check = () => {
  22307. let completed = 0;
  22308. // check all queries and requeue as appropriate
  22309. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  22310. const query = currentOcclusionQueries[ i ];
  22311. if ( query === null ) continue;
  22312. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  22313. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  22314. currentOcclusionQueries[ i ] = null;
  22315. gl.deleteQuery( query );
  22316. completed ++;
  22317. }
  22318. }
  22319. if ( completed < currentOcclusionQueries.length ) {
  22320. requestAnimationFrame( check );
  22321. } else {
  22322. renderContextData.occluded = occluded;
  22323. }
  22324. };
  22325. check();
  22326. }
  22327. }
  22328. isOccluded( renderContext, object ) {
  22329. const renderContextData = this.get( renderContext );
  22330. return renderContextData.occluded && renderContextData.occluded.has( object );
  22331. }
  22332. updateViewport( renderContext ) {
  22333. const gl = this.gl;
  22334. const { x, y, width, height } = renderContext.viewportValue;
  22335. gl.viewport( x, renderContext.height - height - y, width, height );
  22336. }
  22337. setScissorTest( boolean ) {
  22338. const gl = this.gl;
  22339. if ( boolean ) {
  22340. gl.enable( gl.SCISSOR_TEST );
  22341. } else {
  22342. gl.disable( gl.SCISSOR_TEST );
  22343. }
  22344. }
  22345. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  22346. const { gl } = this;
  22347. if ( descriptor === null ) {
  22348. const clearColor = this.getClearColor();
  22349. // premultiply alpha
  22350. clearColor.r *= clearColor.a;
  22351. clearColor.g *= clearColor.a;
  22352. clearColor.b *= clearColor.a;
  22353. descriptor = {
  22354. textures: null,
  22355. clearColorValue: clearColor
  22356. };
  22357. }
  22358. //
  22359. let clear = 0;
  22360. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  22361. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  22362. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  22363. if ( clear !== 0 ) {
  22364. let clearColor;
  22365. if ( descriptor.clearColorValue ) {
  22366. clearColor = descriptor.clearColorValue;
  22367. } else {
  22368. clearColor = this.getClearColor();
  22369. // premultiply alpha
  22370. clearColor.r *= clearColor.a;
  22371. clearColor.g *= clearColor.a;
  22372. clearColor.b *= clearColor.a;
  22373. }
  22374. if ( depth ) this.state.setDepthMask( true );
  22375. if ( descriptor.textures === null ) {
  22376. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  22377. gl.clear( clear );
  22378. } else {
  22379. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  22380. if ( color ) {
  22381. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  22382. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  22383. }
  22384. }
  22385. if ( depth && stencil ) {
  22386. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  22387. } else if ( depth ) {
  22388. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  22389. } else if ( stencil ) {
  22390. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  22391. }
  22392. }
  22393. }
  22394. }
  22395. beginCompute( computeGroup ) {
  22396. const { state, gl } = this;
  22397. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  22398. this.initTimestampQuery( computeGroup );
  22399. }
  22400. compute( computeGroup, computeNode, bindings, pipeline ) {
  22401. const { state, gl } = this;
  22402. if ( ! this.discard ) {
  22403. // required here to handle async behaviour of render.compute()
  22404. gl.enable( gl.RASTERIZER_DISCARD );
  22405. this.discard = true;
  22406. }
  22407. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  22408. const vaoKey = this._getVaoKey( null, attributes );
  22409. const vaoGPU = this.vaoCache[ vaoKey ];
  22410. if ( vaoGPU === undefined ) {
  22411. this._createVao( null, attributes );
  22412. } else {
  22413. gl.bindVertexArray( vaoGPU );
  22414. }
  22415. state.useProgram( programGPU );
  22416. this._bindUniforms( bindings );
  22417. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  22418. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  22419. gl.beginTransformFeedback( gl.POINTS );
  22420. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  22421. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  22422. } else {
  22423. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  22424. }
  22425. gl.endTransformFeedback();
  22426. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  22427. // switch active buffers
  22428. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  22429. const dualAttributeData = transformBuffers[ i ];
  22430. if ( dualAttributeData.pbo ) {
  22431. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  22432. }
  22433. dualAttributeData.switchBuffers();
  22434. }
  22435. }
  22436. finishCompute( computeGroup ) {
  22437. const gl = this.gl;
  22438. this.discard = false;
  22439. gl.disable( gl.RASTERIZER_DISCARD );
  22440. this.prepareTimestampBuffer( computeGroup );
  22441. if ( this._currentContext ) {
  22442. this._setFramebuffer( this._currentContext );
  22443. }
  22444. }
  22445. draw( renderObject/*, info*/ ) {
  22446. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  22447. const { programGPU } = this.get( pipeline );
  22448. const { gl, state } = this;
  22449. const contextData = this.get( context );
  22450. const drawParams = renderObject.getDrawParameters();
  22451. if ( drawParams === null ) return;
  22452. //
  22453. this._bindUniforms( renderObject.getBindings() );
  22454. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  22455. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  22456. state.useProgram( programGPU );
  22457. //
  22458. const renderObjectData = this.get( renderObject );
  22459. let vaoGPU = renderObjectData.staticVao;
  22460. if ( vaoGPU === undefined || renderObjectData.geometryId !== renderObject.geometry.id ) {
  22461. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  22462. vaoGPU = this.vaoCache[ vaoKey ];
  22463. if ( vaoGPU === undefined ) {
  22464. let staticVao;
  22465. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  22466. if ( staticVao ) {
  22467. renderObjectData.staticVao = vaoGPU;
  22468. renderObjectData.geometryId = renderObject.geometry.id;
  22469. }
  22470. }
  22471. }
  22472. gl.bindVertexArray( vaoGPU );
  22473. //
  22474. const index = renderObject.getIndex();
  22475. //
  22476. const lastObject = contextData.lastOcclusionObject;
  22477. if ( lastObject !== object && lastObject !== undefined ) {
  22478. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  22479. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  22480. contextData.occlusionQueryIndex ++;
  22481. }
  22482. if ( object.occlusionTest === true ) {
  22483. const query = gl.createQuery();
  22484. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  22485. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  22486. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  22487. }
  22488. contextData.lastOcclusionObject = object;
  22489. }
  22490. //
  22491. const renderer = this.bufferRenderer;
  22492. if ( object.isPoints ) renderer.mode = gl.POINTS;
  22493. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  22494. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  22495. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  22496. else {
  22497. if ( material.wireframe === true ) {
  22498. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  22499. renderer.mode = gl.LINES;
  22500. } else {
  22501. renderer.mode = gl.TRIANGLES;
  22502. }
  22503. }
  22504. //
  22505. const { vertexCount, instanceCount } = drawParams;
  22506. let { firstVertex } = drawParams;
  22507. renderer.object = object;
  22508. if ( index !== null ) {
  22509. firstVertex *= index.array.BYTES_PER_ELEMENT;
  22510. const indexData = this.get( index );
  22511. renderer.index = index.count;
  22512. renderer.type = indexData.type;
  22513. } else {
  22514. renderer.index = 0;
  22515. }
  22516. if ( object.isBatchedMesh ) {
  22517. if ( object._multiDrawInstances !== null ) {
  22518. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  22519. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  22520. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  22521. } else {
  22522. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  22523. }
  22524. } else if ( instanceCount > 1 ) {
  22525. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  22526. } else {
  22527. renderer.render( firstVertex, vertexCount );
  22528. }
  22529. //
  22530. gl.bindVertexArray( null );
  22531. }
  22532. needsRenderUpdate( /*renderObject*/ ) {
  22533. return false;
  22534. }
  22535. getRenderCacheKey( /*renderObject*/ ) {
  22536. return '';
  22537. }
  22538. // textures
  22539. createDefaultTexture( texture ) {
  22540. this.textureUtils.createDefaultTexture( texture );
  22541. }
  22542. createTexture( texture, options ) {
  22543. this.textureUtils.createTexture( texture, options );
  22544. }
  22545. updateTexture( texture, options ) {
  22546. this.textureUtils.updateTexture( texture, options );
  22547. }
  22548. generateMipmaps( texture ) {
  22549. this.textureUtils.generateMipmaps( texture );
  22550. }
  22551. destroyTexture( texture ) {
  22552. this.textureUtils.destroyTexture( texture );
  22553. }
  22554. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  22555. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  22556. }
  22557. createSampler( /*texture*/ ) {
  22558. //console.warn( 'Abstract class.' );
  22559. }
  22560. destroySampler() {}
  22561. // node builder
  22562. createNodeBuilder( object, renderer ) {
  22563. return new GLSLNodeBuilder( object, renderer );
  22564. }
  22565. // program
  22566. createProgram( program ) {
  22567. const gl = this.gl;
  22568. const { stage, code } = program;
  22569. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  22570. gl.shaderSource( shader, code );
  22571. gl.compileShader( shader );
  22572. this.set( program, {
  22573. shaderGPU: shader
  22574. } );
  22575. }
  22576. destroyProgram( /*program*/ ) {
  22577. console.warn( 'Abstract class.' );
  22578. }
  22579. createRenderPipeline( renderObject, promises ) {
  22580. const gl = this.gl;
  22581. const pipeline = renderObject.pipeline;
  22582. // Program
  22583. const { fragmentProgram, vertexProgram } = pipeline;
  22584. const programGPU = gl.createProgram();
  22585. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  22586. const vertexShader = this.get( vertexProgram ).shaderGPU;
  22587. gl.attachShader( programGPU, fragmentShader );
  22588. gl.attachShader( programGPU, vertexShader );
  22589. gl.linkProgram( programGPU );
  22590. this.set( pipeline, {
  22591. programGPU,
  22592. fragmentShader,
  22593. vertexShader
  22594. } );
  22595. if ( promises !== null && this.parallel ) {
  22596. const p = new Promise( ( resolve /*, reject*/ ) => {
  22597. const parallel = this.parallel;
  22598. const checkStatus = () => {
  22599. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  22600. this._completeCompile( renderObject, pipeline );
  22601. resolve();
  22602. } else {
  22603. requestAnimationFrame( checkStatus );
  22604. }
  22605. };
  22606. checkStatus();
  22607. } );
  22608. promises.push( p );
  22609. return;
  22610. }
  22611. this._completeCompile( renderObject, pipeline );
  22612. }
  22613. _handleSource( string, errorLine ) {
  22614. const lines = string.split( '\n' );
  22615. const lines2 = [];
  22616. const from = Math.max( errorLine - 6, 0 );
  22617. const to = Math.min( errorLine + 6, lines.length );
  22618. for ( let i = from; i < to; i ++ ) {
  22619. const line = i + 1;
  22620. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  22621. }
  22622. return lines2.join( '\n' );
  22623. }
  22624. _getShaderErrors( gl, shader, type ) {
  22625. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  22626. const errors = gl.getShaderInfoLog( shader ).trim();
  22627. if ( status && errors === '' ) return '';
  22628. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  22629. if ( errorMatches ) {
  22630. const errorLine = parseInt( errorMatches[ 1 ] );
  22631. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  22632. } else {
  22633. return errors;
  22634. }
  22635. }
  22636. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  22637. if ( this.renderer.debug.checkShaderErrors ) {
  22638. const gl = this.gl;
  22639. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  22640. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  22641. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  22642. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  22643. } else {
  22644. // default error reporting
  22645. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  22646. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  22647. console.error(
  22648. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  22649. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  22650. 'Program Info Log: ' + programLog + '\n' +
  22651. vertexErrors + '\n' +
  22652. fragmentErrors
  22653. );
  22654. }
  22655. } else if ( programLog !== '' ) {
  22656. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  22657. }
  22658. }
  22659. }
  22660. _completeCompile( renderObject, pipeline ) {
  22661. const { state, gl } = this;
  22662. const pipelineData = this.get( pipeline );
  22663. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  22664. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  22665. this._logProgramError( programGPU, fragmentShader, vertexShader );
  22666. }
  22667. state.useProgram( programGPU );
  22668. // Bindings
  22669. const bindings = renderObject.getBindings();
  22670. this._setupBindings( bindings, programGPU );
  22671. //
  22672. this.set( pipeline, {
  22673. programGPU
  22674. } );
  22675. }
  22676. createComputePipeline( computePipeline, bindings ) {
  22677. const { state, gl } = this;
  22678. // Program
  22679. const fragmentProgram = {
  22680. stage: 'fragment',
  22681. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  22682. };
  22683. this.createProgram( fragmentProgram );
  22684. const { computeProgram } = computePipeline;
  22685. const programGPU = gl.createProgram();
  22686. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  22687. const vertexShader = this.get( computeProgram ).shaderGPU;
  22688. const transforms = computeProgram.transforms;
  22689. const transformVaryingNames = [];
  22690. const transformAttributeNodes = [];
  22691. for ( let i = 0; i < transforms.length; i ++ ) {
  22692. const transform = transforms[ i ];
  22693. transformVaryingNames.push( transform.varyingName );
  22694. transformAttributeNodes.push( transform.attributeNode );
  22695. }
  22696. gl.attachShader( programGPU, fragmentShader );
  22697. gl.attachShader( programGPU, vertexShader );
  22698. gl.transformFeedbackVaryings(
  22699. programGPU,
  22700. transformVaryingNames,
  22701. gl.SEPARATE_ATTRIBS
  22702. );
  22703. gl.linkProgram( programGPU );
  22704. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  22705. this._logProgramError( programGPU, fragmentShader, vertexShader );
  22706. }
  22707. state.useProgram( programGPU );
  22708. // Bindings
  22709. this._setupBindings( bindings, programGPU );
  22710. const attributeNodes = computeProgram.attributes;
  22711. const attributes = [];
  22712. const transformBuffers = [];
  22713. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  22714. const attribute = attributeNodes[ i ].node.attribute;
  22715. attributes.push( attribute );
  22716. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  22717. }
  22718. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  22719. const attribute = transformAttributeNodes[ i ].attribute;
  22720. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  22721. const attributeData = this.get( attribute );
  22722. transformBuffers.push( attributeData );
  22723. }
  22724. //
  22725. this.set( computePipeline, {
  22726. programGPU,
  22727. transformBuffers,
  22728. attributes
  22729. } );
  22730. }
  22731. createBindings( bindGroup, bindings ) {
  22732. if ( this._knownBindings.has( bindings ) === false ) {
  22733. this._knownBindings.add( bindings );
  22734. let uniformBuffers = 0;
  22735. let textures = 0;
  22736. for ( const bindGroup of bindings ) {
  22737. this.set( bindGroup, {
  22738. textures: textures,
  22739. uniformBuffers: uniformBuffers
  22740. } );
  22741. for ( const binding of bindGroup.bindings ) {
  22742. if ( binding.isUniformBuffer ) uniformBuffers ++;
  22743. if ( binding.isSampledTexture ) textures ++;
  22744. }
  22745. }
  22746. }
  22747. this.updateBindings( bindGroup, bindings );
  22748. }
  22749. updateBindings( bindGroup /*, bindings*/ ) {
  22750. const { gl } = this;
  22751. const bindGroupData = this.get( bindGroup );
  22752. let i = bindGroupData.uniformBuffers;
  22753. let t = bindGroupData.textures;
  22754. for ( const binding of bindGroup.bindings ) {
  22755. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  22756. const data = binding.buffer;
  22757. const bufferGPU = gl.createBuffer();
  22758. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  22759. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  22760. this.set( binding, {
  22761. index: i ++,
  22762. bufferGPU
  22763. } );
  22764. } else if ( binding.isSampledTexture ) {
  22765. const { textureGPU, glTextureType } = this.get( binding.texture );
  22766. this.set( binding, {
  22767. index: t ++,
  22768. textureGPU,
  22769. glTextureType
  22770. } );
  22771. }
  22772. }
  22773. }
  22774. updateBinding( binding ) {
  22775. const gl = this.gl;
  22776. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  22777. const bindingData = this.get( binding );
  22778. const bufferGPU = bindingData.bufferGPU;
  22779. const data = binding.buffer;
  22780. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  22781. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  22782. }
  22783. }
  22784. // attributes
  22785. createIndexAttribute( attribute ) {
  22786. const gl = this.gl;
  22787. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  22788. }
  22789. createAttribute( attribute ) {
  22790. if ( this.has( attribute ) ) return;
  22791. const gl = this.gl;
  22792. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  22793. }
  22794. createStorageAttribute( attribute ) {
  22795. if ( this.has( attribute ) ) return;
  22796. const gl = this.gl;
  22797. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  22798. }
  22799. updateAttribute( attribute ) {
  22800. this.attributeUtils.updateAttribute( attribute );
  22801. }
  22802. destroyAttribute( attribute ) {
  22803. this.attributeUtils.destroyAttribute( attribute );
  22804. }
  22805. updateSize() {
  22806. //console.warn( 'Abstract class.' );
  22807. }
  22808. hasFeature( name ) {
  22809. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  22810. const extensions = this.extensions;
  22811. for ( let i = 0; i < keysMatching.length; i ++ ) {
  22812. if ( extensions.has( keysMatching[ i ] ) ) return true;
  22813. }
  22814. return false;
  22815. }
  22816. getMaxAnisotropy() {
  22817. return this.capabilities.getMaxAnisotropy();
  22818. }
  22819. copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level ) {
  22820. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  22821. }
  22822. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  22823. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  22824. }
  22825. _setFramebuffer( descriptor ) {
  22826. const { gl, state } = this;
  22827. let currentFrameBuffer = null;
  22828. if ( descriptor.textures !== null ) {
  22829. const renderTarget = descriptor.renderTarget;
  22830. const renderTargetContextData = this.get( renderTarget );
  22831. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  22832. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  22833. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  22834. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  22835. const cacheKey = getCacheKey( descriptor );
  22836. let fb;
  22837. if ( isCube ) {
  22838. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  22839. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  22840. } else {
  22841. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  22842. fb = renderTargetContextData.framebuffers[ cacheKey ];
  22843. }
  22844. if ( fb === undefined ) {
  22845. fb = gl.createFramebuffer();
  22846. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  22847. const textures = descriptor.textures;
  22848. if ( isCube ) {
  22849. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  22850. const { textureGPU } = this.get( textures[ 0 ] );
  22851. const cubeFace = this.renderer._activeCubeFace;
  22852. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  22853. } else {
  22854. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  22855. for ( let i = 0; i < textures.length; i ++ ) {
  22856. const texture = textures[ i ];
  22857. const textureData = this.get( texture );
  22858. textureData.renderTarget = descriptor.renderTarget;
  22859. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  22860. const attachment = gl.COLOR_ATTACHMENT0 + i;
  22861. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  22862. }
  22863. state.drawBuffers( descriptor, fb );
  22864. }
  22865. if ( descriptor.depthTexture !== null ) {
  22866. const textureData = this.get( descriptor.depthTexture );
  22867. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  22868. textureData.renderTarget = descriptor.renderTarget;
  22869. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  22870. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  22871. }
  22872. }
  22873. if ( samples > 0 ) {
  22874. if ( msaaFb === undefined ) {
  22875. const invalidationArray = [];
  22876. msaaFb = gl.createFramebuffer();
  22877. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  22878. const msaaRenderbuffers = [];
  22879. const textures = descriptor.textures;
  22880. for ( let i = 0; i < textures.length; i ++ ) {
  22881. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  22882. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  22883. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  22884. if ( depthBuffer ) {
  22885. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  22886. invalidationArray.push( depthStyle );
  22887. }
  22888. const texture = descriptor.textures[ i ];
  22889. const textureData = this.get( texture );
  22890. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  22891. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  22892. }
  22893. renderTargetContextData.msaaFrameBuffer = msaaFb;
  22894. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  22895. if ( depthRenderbuffer === undefined ) {
  22896. depthRenderbuffer = gl.createRenderbuffer();
  22897. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor );
  22898. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  22899. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  22900. invalidationArray.push( depthStyle );
  22901. }
  22902. renderTargetContextData.invalidationArray = invalidationArray;
  22903. }
  22904. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  22905. } else {
  22906. currentFrameBuffer = fb;
  22907. }
  22908. }
  22909. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  22910. }
  22911. _getVaoKey( index, attributes ) {
  22912. let key = [];
  22913. if ( index !== null ) {
  22914. const indexData = this.get( index );
  22915. key += ':' + indexData.id;
  22916. }
  22917. for ( let i = 0; i < attributes.length; i ++ ) {
  22918. const attributeData = this.get( attributes[ i ] );
  22919. key += ':' + attributeData.id;
  22920. }
  22921. return key;
  22922. }
  22923. _createVao( index, attributes ) {
  22924. const { gl } = this;
  22925. const vaoGPU = gl.createVertexArray();
  22926. let key = '';
  22927. let staticVao = true;
  22928. gl.bindVertexArray( vaoGPU );
  22929. if ( index !== null ) {
  22930. const indexData = this.get( index );
  22931. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  22932. key += ':' + indexData.id;
  22933. }
  22934. for ( let i = 0; i < attributes.length; i ++ ) {
  22935. const attribute = attributes[ i ];
  22936. const attributeData = this.get( attribute );
  22937. key += ':' + attributeData.id;
  22938. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  22939. gl.enableVertexAttribArray( i );
  22940. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  22941. let stride, offset;
  22942. if ( attribute.isInterleavedBufferAttribute === true ) {
  22943. stride = attribute.data.stride * attributeData.bytesPerElement;
  22944. offset = attribute.offset * attributeData.bytesPerElement;
  22945. } else {
  22946. stride = 0;
  22947. offset = 0;
  22948. }
  22949. if ( attributeData.isInteger ) {
  22950. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  22951. } else {
  22952. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  22953. }
  22954. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  22955. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  22956. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  22957. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  22958. }
  22959. }
  22960. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  22961. this.vaoCache[ key ] = vaoGPU;
  22962. return { vaoGPU, staticVao };
  22963. }
  22964. _getTransformFeedback( transformBuffers ) {
  22965. let key = '';
  22966. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  22967. key += ':' + transformBuffers[ i ].id;
  22968. }
  22969. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  22970. if ( transformFeedbackGPU !== undefined ) {
  22971. return transformFeedbackGPU;
  22972. }
  22973. const { gl } = this;
  22974. transformFeedbackGPU = gl.createTransformFeedback();
  22975. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  22976. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  22977. const attributeData = transformBuffers[ i ];
  22978. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  22979. }
  22980. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  22981. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  22982. return transformFeedbackGPU;
  22983. }
  22984. _setupBindings( bindings, programGPU ) {
  22985. const gl = this.gl;
  22986. for ( const bindGroup of bindings ) {
  22987. for ( const binding of bindGroup.bindings ) {
  22988. const bindingData = this.get( binding );
  22989. const index = bindingData.index;
  22990. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  22991. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  22992. gl.uniformBlockBinding( programGPU, location, index );
  22993. } else if ( binding.isSampledTexture ) {
  22994. const location = gl.getUniformLocation( programGPU, binding.name );
  22995. gl.uniform1i( location, index );
  22996. }
  22997. }
  22998. }
  22999. }
  23000. _bindUniforms( bindings ) {
  23001. const { gl, state } = this;
  23002. for ( const bindGroup of bindings ) {
  23003. for ( const binding of bindGroup.bindings ) {
  23004. const bindingData = this.get( binding );
  23005. const index = bindingData.index;
  23006. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  23007. // TODO USE bindBufferRange to group multiple uniform buffers
  23008. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  23009. } else if ( binding.isSampledTexture ) {
  23010. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  23011. }
  23012. }
  23013. }
  23014. }
  23015. dispose() {
  23016. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  23017. }
  23018. }
  23019. const GPUPrimitiveTopology = {
  23020. PointList: 'point-list',
  23021. LineList: 'line-list',
  23022. LineStrip: 'line-strip',
  23023. TriangleList: 'triangle-list',
  23024. TriangleStrip: 'triangle-strip',
  23025. };
  23026. const GPUCompareFunction = {
  23027. Never: 'never',
  23028. Less: 'less',
  23029. Equal: 'equal',
  23030. LessEqual: 'less-equal',
  23031. Greater: 'greater',
  23032. NotEqual: 'not-equal',
  23033. GreaterEqual: 'greater-equal',
  23034. Always: 'always'
  23035. };
  23036. const GPUStoreOp = {
  23037. Store: 'store',
  23038. Discard: 'discard'
  23039. };
  23040. const GPULoadOp = {
  23041. Load: 'load',
  23042. Clear: 'clear'
  23043. };
  23044. const GPUFrontFace = {
  23045. CCW: 'ccw',
  23046. CW: 'cw'
  23047. };
  23048. const GPUCullMode = {
  23049. None: 'none',
  23050. Front: 'front',
  23051. Back: 'back'
  23052. };
  23053. const GPUIndexFormat = {
  23054. Uint16: 'uint16',
  23055. Uint32: 'uint32'
  23056. };
  23057. const GPUTextureFormat = {
  23058. // 8-bit formats
  23059. R8Unorm: 'r8unorm',
  23060. R8Snorm: 'r8snorm',
  23061. R8Uint: 'r8uint',
  23062. R8Sint: 'r8sint',
  23063. // 16-bit formats
  23064. R16Uint: 'r16uint',
  23065. R16Sint: 'r16sint',
  23066. R16Float: 'r16float',
  23067. RG8Unorm: 'rg8unorm',
  23068. RG8Snorm: 'rg8snorm',
  23069. RG8Uint: 'rg8uint',
  23070. RG8Sint: 'rg8sint',
  23071. // 32-bit formats
  23072. R32Uint: 'r32uint',
  23073. R32Sint: 'r32sint',
  23074. R32Float: 'r32float',
  23075. RG16Uint: 'rg16uint',
  23076. RG16Sint: 'rg16sint',
  23077. RG16Float: 'rg16float',
  23078. RGBA8Unorm: 'rgba8unorm',
  23079. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  23080. RGBA8Snorm: 'rgba8snorm',
  23081. RGBA8Uint: 'rgba8uint',
  23082. RGBA8Sint: 'rgba8sint',
  23083. BGRA8Unorm: 'bgra8unorm',
  23084. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  23085. // Packed 32-bit formats
  23086. RGB9E5UFloat: 'rgb9e5ufloat',
  23087. RGB10A2Unorm: 'rgb10a2unorm',
  23088. RG11B10uFloat: 'rgb10a2unorm',
  23089. // 64-bit formats
  23090. RG32Uint: 'rg32uint',
  23091. RG32Sint: 'rg32sint',
  23092. RG32Float: 'rg32float',
  23093. RGBA16Uint: 'rgba16uint',
  23094. RGBA16Sint: 'rgba16sint',
  23095. RGBA16Float: 'rgba16float',
  23096. // 128-bit formats
  23097. RGBA32Uint: 'rgba32uint',
  23098. RGBA32Sint: 'rgba32sint',
  23099. RGBA32Float: 'rgba32float',
  23100. // Depth and stencil formats
  23101. Stencil8: 'stencil8',
  23102. Depth16Unorm: 'depth16unorm',
  23103. Depth24Plus: 'depth24plus',
  23104. Depth24PlusStencil8: 'depth24plus-stencil8',
  23105. Depth32Float: 'depth32float',
  23106. // 'depth32float-stencil8' extension
  23107. Depth32FloatStencil8: 'depth32float-stencil8',
  23108. // BC compressed formats usable if 'texture-compression-bc' is both
  23109. // supported by the device/user agent and enabled in requestDevice.
  23110. BC1RGBAUnorm: 'bc1-rgba-unorm',
  23111. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  23112. BC2RGBAUnorm: 'bc2-rgba-unorm',
  23113. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  23114. BC3RGBAUnorm: 'bc3-rgba-unorm',
  23115. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  23116. BC4RUnorm: 'bc4-r-unorm',
  23117. BC4RSnorm: 'bc4-r-snorm',
  23118. BC5RGUnorm: 'bc5-rg-unorm',
  23119. BC5RGSnorm: 'bc5-rg-snorm',
  23120. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  23121. BC6HRGBFloat: 'bc6h-rgb-float',
  23122. BC7RGBAUnorm: 'bc7-rgba-unorm',
  23123. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  23124. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  23125. // supported by the device/user agent and enabled in requestDevice.
  23126. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  23127. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  23128. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  23129. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  23130. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  23131. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  23132. EACR11Unorm: 'eac-r11unorm',
  23133. EACR11Snorm: 'eac-r11snorm',
  23134. EACRG11Unorm: 'eac-rg11unorm',
  23135. EACRG11Snorm: 'eac-rg11snorm',
  23136. // ASTC compressed formats usable if 'texture-compression-astc' is both
  23137. // supported by the device/user agent and enabled in requestDevice.
  23138. ASTC4x4Unorm: 'astc-4x4-unorm',
  23139. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  23140. ASTC5x4Unorm: 'astc-5x4-unorm',
  23141. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  23142. ASTC5x5Unorm: 'astc-5x5-unorm',
  23143. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  23144. ASTC6x5Unorm: 'astc-6x5-unorm',
  23145. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  23146. ASTC6x6Unorm: 'astc-6x6-unorm',
  23147. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  23148. ASTC8x5Unorm: 'astc-8x5-unorm',
  23149. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  23150. ASTC8x6Unorm: 'astc-8x6-unorm',
  23151. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  23152. ASTC8x8Unorm: 'astc-8x8-unorm',
  23153. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  23154. ASTC10x5Unorm: 'astc-10x5-unorm',
  23155. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  23156. ASTC10x6Unorm: 'astc-10x6-unorm',
  23157. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  23158. ASTC10x8Unorm: 'astc-10x8-unorm',
  23159. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  23160. ASTC10x10Unorm: 'astc-10x10-unorm',
  23161. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  23162. ASTC12x10Unorm: 'astc-12x10-unorm',
  23163. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  23164. ASTC12x12Unorm: 'astc-12x12-unorm',
  23165. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  23166. };
  23167. const GPUAddressMode = {
  23168. ClampToEdge: 'clamp-to-edge',
  23169. Repeat: 'repeat',
  23170. MirrorRepeat: 'mirror-repeat'
  23171. };
  23172. const GPUFilterMode = {
  23173. Linear: 'linear',
  23174. Nearest: 'nearest'
  23175. };
  23176. const GPUBlendFactor = {
  23177. Zero: 'zero',
  23178. One: 'one',
  23179. Src: 'src',
  23180. OneMinusSrc: 'one-minus-src',
  23181. SrcAlpha: 'src-alpha',
  23182. OneMinusSrcAlpha: 'one-minus-src-alpha',
  23183. Dst: 'dst',
  23184. OneMinusDstColor: 'one-minus-dst',
  23185. DstAlpha: 'dst-alpha',
  23186. OneMinusDstAlpha: 'one-minus-dst-alpha',
  23187. SrcAlphaSaturated: 'src-alpha-saturated',
  23188. Constant: 'constant',
  23189. OneMinusConstant: 'one-minus-constant'
  23190. };
  23191. const GPUBlendOperation = {
  23192. Add: 'add',
  23193. Subtract: 'subtract',
  23194. ReverseSubtract: 'reverse-subtract',
  23195. Min: 'min',
  23196. Max: 'max'
  23197. };
  23198. const GPUColorWriteFlags = {
  23199. None: 0,
  23200. Red: 0x1,
  23201. Green: 0x2,
  23202. Blue: 0x4,
  23203. Alpha: 0x8,
  23204. All: 0xF
  23205. };
  23206. const GPUStencilOperation = {
  23207. Keep: 'keep',
  23208. Zero: 'zero',
  23209. Replace: 'replace',
  23210. Invert: 'invert',
  23211. IncrementClamp: 'increment-clamp',
  23212. DecrementClamp: 'decrement-clamp',
  23213. IncrementWrap: 'increment-wrap',
  23214. DecrementWrap: 'decrement-wrap'
  23215. };
  23216. const GPUBufferBindingType = {
  23217. Uniform: 'uniform',
  23218. Storage: 'storage',
  23219. ReadOnlyStorage: 'read-only-storage'
  23220. };
  23221. const GPUStorageTextureAccess = {
  23222. WriteOnly: 'write-only',
  23223. ReadOnly: 'read-only',
  23224. ReadWrite: 'read-write',
  23225. };
  23226. const GPUTextureSampleType = {
  23227. Float: 'float',
  23228. UnfilterableFloat: 'unfilterable-float',
  23229. Depth: 'depth',
  23230. SInt: 'sint',
  23231. UInt: 'uint'
  23232. };
  23233. const GPUTextureDimension = {
  23234. OneD: '1d',
  23235. TwoD: '2d',
  23236. ThreeD: '3d'
  23237. };
  23238. const GPUTextureViewDimension = {
  23239. OneD: '1d',
  23240. TwoD: '2d',
  23241. TwoDArray: '2d-array',
  23242. Cube: 'cube',
  23243. CubeArray: 'cube-array',
  23244. ThreeD: '3d'
  23245. };
  23246. const GPUTextureAspect = {
  23247. All: 'all',
  23248. StencilOnly: 'stencil-only',
  23249. DepthOnly: 'depth-only'
  23250. };
  23251. const GPUInputStepMode = {
  23252. Vertex: 'vertex',
  23253. Instance: 'instance'
  23254. };
  23255. const GPUFeatureName = {
  23256. DepthClipControl: 'depth-clip-control',
  23257. Depth32FloatStencil8: 'depth32float-stencil8',
  23258. TextureCompressionBC: 'texture-compression-bc',
  23259. TextureCompressionETC2: 'texture-compression-etc2',
  23260. TextureCompressionASTC: 'texture-compression-astc',
  23261. TimestampQuery: 'timestamp-query',
  23262. IndirectFirstInstance: 'indirect-first-instance',
  23263. ShaderF16: 'shader-f16',
  23264. RG11B10UFloat: 'rg11b10ufloat-renderable',
  23265. BGRA8UNormStorage: 'bgra8unorm-storage',
  23266. Float32Filterable: 'float32-filterable',
  23267. ClipDistances: 'clip-distances',
  23268. DualSourceBlending: 'dual-source-blending',
  23269. Subgroups: 'subgroups'
  23270. };
  23271. class Sampler extends Binding {
  23272. constructor( name, texture ) {
  23273. super( name );
  23274. this.texture = texture;
  23275. this.version = texture ? texture.version : 0;
  23276. this.isSampler = true;
  23277. }
  23278. }
  23279. class NodeSampler extends Sampler {
  23280. constructor( name, textureNode, groupNode ) {
  23281. super( name, textureNode ? textureNode.value : null );
  23282. this.textureNode = textureNode;
  23283. this.groupNode = groupNode;
  23284. }
  23285. update() {
  23286. this.texture = this.textureNode.value;
  23287. }
  23288. }
  23289. class StorageBuffer extends Buffer {
  23290. constructor( name, attribute ) {
  23291. super( name, attribute ? attribute.array : null );
  23292. this.attribute = attribute;
  23293. this.isStorageBuffer = true;
  23294. }
  23295. }
  23296. let _id = 0;
  23297. class NodeStorageBuffer extends StorageBuffer {
  23298. constructor( nodeUniform, groupNode ) {
  23299. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  23300. this.nodeUniform = nodeUniform;
  23301. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  23302. this.groupNode = groupNode;
  23303. }
  23304. get buffer() {
  23305. return this.nodeUniform.value;
  23306. }
  23307. }
  23308. class WebGPUTexturePassUtils extends DataMap {
  23309. constructor( device ) {
  23310. super();
  23311. this.device = device;
  23312. const mipmapVertexSource = `
  23313. struct VarysStruct {
  23314. @builtin( position ) Position: vec4<f32>,
  23315. @location( 0 ) vTex : vec2<f32>
  23316. };
  23317. @vertex
  23318. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  23319. var Varys : VarysStruct;
  23320. var pos = array< vec2<f32>, 4 >(
  23321. vec2<f32>( -1.0, 1.0 ),
  23322. vec2<f32>( 1.0, 1.0 ),
  23323. vec2<f32>( -1.0, -1.0 ),
  23324. vec2<f32>( 1.0, -1.0 )
  23325. );
  23326. var tex = array< vec2<f32>, 4 >(
  23327. vec2<f32>( 0.0, 0.0 ),
  23328. vec2<f32>( 1.0, 0.0 ),
  23329. vec2<f32>( 0.0, 1.0 ),
  23330. vec2<f32>( 1.0, 1.0 )
  23331. );
  23332. Varys.vTex = tex[ vertexIndex ];
  23333. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  23334. return Varys;
  23335. }
  23336. `;
  23337. const mipmapFragmentSource = `
  23338. @group( 0 ) @binding( 0 )
  23339. var imgSampler : sampler;
  23340. @group( 0 ) @binding( 1 )
  23341. var img : texture_2d<f32>;
  23342. @fragment
  23343. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  23344. return textureSample( img, imgSampler, vTex );
  23345. }
  23346. `;
  23347. const flipYFragmentSource = `
  23348. @group( 0 ) @binding( 0 )
  23349. var imgSampler : sampler;
  23350. @group( 0 ) @binding( 1 )
  23351. var img : texture_2d<f32>;
  23352. @fragment
  23353. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  23354. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  23355. }
  23356. `;
  23357. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  23358. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  23359. // We'll need a new pipeline for every texture format used.
  23360. this.transferPipelines = {};
  23361. this.flipYPipelines = {};
  23362. this.mipmapVertexShaderModule = device.createShaderModule( {
  23363. label: 'mipmapVertex',
  23364. code: mipmapVertexSource
  23365. } );
  23366. this.mipmapFragmentShaderModule = device.createShaderModule( {
  23367. label: 'mipmapFragment',
  23368. code: mipmapFragmentSource
  23369. } );
  23370. this.flipYFragmentShaderModule = device.createShaderModule( {
  23371. label: 'flipYFragment',
  23372. code: flipYFragmentSource
  23373. } );
  23374. }
  23375. getTransferPipeline( format ) {
  23376. let pipeline = this.transferPipelines[ format ];
  23377. if ( pipeline === undefined ) {
  23378. pipeline = this.device.createRenderPipeline( {
  23379. label: `mipmap-${ format }`,
  23380. vertex: {
  23381. module: this.mipmapVertexShaderModule,
  23382. entryPoint: 'main'
  23383. },
  23384. fragment: {
  23385. module: this.mipmapFragmentShaderModule,
  23386. entryPoint: 'main',
  23387. targets: [ { format } ]
  23388. },
  23389. primitive: {
  23390. topology: GPUPrimitiveTopology.TriangleStrip,
  23391. stripIndexFormat: GPUIndexFormat.Uint32
  23392. },
  23393. layout: 'auto'
  23394. } );
  23395. this.transferPipelines[ format ] = pipeline;
  23396. }
  23397. return pipeline;
  23398. }
  23399. getFlipYPipeline( format ) {
  23400. let pipeline = this.flipYPipelines[ format ];
  23401. if ( pipeline === undefined ) {
  23402. pipeline = this.device.createRenderPipeline( {
  23403. label: `flipY-${ format }`,
  23404. vertex: {
  23405. module: this.mipmapVertexShaderModule,
  23406. entryPoint: 'main'
  23407. },
  23408. fragment: {
  23409. module: this.flipYFragmentShaderModule,
  23410. entryPoint: 'main',
  23411. targets: [ { format } ]
  23412. },
  23413. primitive: {
  23414. topology: GPUPrimitiveTopology.TriangleStrip,
  23415. stripIndexFormat: GPUIndexFormat.Uint32
  23416. },
  23417. layout: 'auto'
  23418. } );
  23419. this.flipYPipelines[ format ] = pipeline;
  23420. }
  23421. return pipeline;
  23422. }
  23423. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  23424. const format = textureGPUDescriptor.format;
  23425. const { width, height } = textureGPUDescriptor.size;
  23426. const transferPipeline = this.getTransferPipeline( format );
  23427. const flipYPipeline = this.getFlipYPipeline( format );
  23428. const tempTexture = this.device.createTexture( {
  23429. size: { width, height, depthOrArrayLayers: 1 },
  23430. format,
  23431. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  23432. } );
  23433. const srcView = textureGPU.createView( {
  23434. baseMipLevel: 0,
  23435. mipLevelCount: 1,
  23436. dimension: GPUTextureViewDimension.TwoD,
  23437. baseArrayLayer
  23438. } );
  23439. const dstView = tempTexture.createView( {
  23440. baseMipLevel: 0,
  23441. mipLevelCount: 1,
  23442. dimension: GPUTextureViewDimension.TwoD,
  23443. baseArrayLayer: 0
  23444. } );
  23445. const commandEncoder = this.device.createCommandEncoder( {} );
  23446. const pass = ( pipeline, sourceView, destinationView ) => {
  23447. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  23448. const bindGroup = this.device.createBindGroup( {
  23449. layout: bindGroupLayout,
  23450. entries: [ {
  23451. binding: 0,
  23452. resource: this.flipYSampler
  23453. }, {
  23454. binding: 1,
  23455. resource: sourceView
  23456. } ]
  23457. } );
  23458. const passEncoder = commandEncoder.beginRenderPass( {
  23459. colorAttachments: [ {
  23460. view: destinationView,
  23461. loadOp: GPULoadOp.Clear,
  23462. storeOp: GPUStoreOp.Store,
  23463. clearValue: [ 0, 0, 0, 0 ]
  23464. } ]
  23465. } );
  23466. passEncoder.setPipeline( pipeline );
  23467. passEncoder.setBindGroup( 0, bindGroup );
  23468. passEncoder.draw( 4, 1, 0, 0 );
  23469. passEncoder.end();
  23470. };
  23471. pass( transferPipeline, srcView, dstView );
  23472. pass( flipYPipeline, dstView, srcView );
  23473. this.device.queue.submit( [ commandEncoder.finish() ] );
  23474. tempTexture.destroy();
  23475. }
  23476. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  23477. const textureData = this.get( textureGPU );
  23478. if ( textureData.useCount === undefined ) {
  23479. textureData.useCount = 0;
  23480. textureData.layers = [];
  23481. }
  23482. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  23483. const commandEncoder = this.device.createCommandEncoder( {} );
  23484. this._mipmapRunBundles( commandEncoder, passes );
  23485. this.device.queue.submit( [ commandEncoder.finish() ] );
  23486. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  23487. textureData.useCount ++;
  23488. }
  23489. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  23490. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  23491. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  23492. let srcView = textureGPU.createView( {
  23493. baseMipLevel: 0,
  23494. mipLevelCount: 1,
  23495. dimension: GPUTextureViewDimension.TwoD,
  23496. baseArrayLayer
  23497. } );
  23498. const passes = [];
  23499. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  23500. const bindGroup = this.device.createBindGroup( {
  23501. layout: bindGroupLayout,
  23502. entries: [ {
  23503. binding: 0,
  23504. resource: this.mipmapSampler
  23505. }, {
  23506. binding: 1,
  23507. resource: srcView
  23508. } ]
  23509. } );
  23510. const dstView = textureGPU.createView( {
  23511. baseMipLevel: i,
  23512. mipLevelCount: 1,
  23513. dimension: GPUTextureViewDimension.TwoD,
  23514. baseArrayLayer
  23515. } );
  23516. const passDescriptor = {
  23517. colorAttachments: [ {
  23518. view: dstView,
  23519. loadOp: GPULoadOp.Clear,
  23520. storeOp: GPUStoreOp.Store,
  23521. clearValue: [ 0, 0, 0, 0 ]
  23522. } ]
  23523. };
  23524. const passEncoder = this.device.createRenderBundleEncoder( {
  23525. colorFormats: [ textureGPUDescriptor.format ]
  23526. } );
  23527. passEncoder.setPipeline( pipeline );
  23528. passEncoder.setBindGroup( 0, bindGroup );
  23529. passEncoder.draw( 4, 1, 0, 0 );
  23530. passes.push( {
  23531. renderBundles: [ passEncoder.finish() ],
  23532. passDescriptor
  23533. } );
  23534. srcView = dstView;
  23535. }
  23536. return passes;
  23537. }
  23538. _mipmapRunBundles( commandEncoder, passes ) {
  23539. const levels = passes.length;
  23540. for ( let i = 0; i < levels; i ++ ) {
  23541. const pass = passes[ i ];
  23542. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  23543. passEncoder.executeBundles( pass.renderBundles );
  23544. passEncoder.end();
  23545. }
  23546. }
  23547. }
  23548. const _compareToWebGPU = {
  23549. [ NeverCompare ]: 'never',
  23550. [ LessCompare ]: 'less',
  23551. [ EqualCompare ]: 'equal',
  23552. [ LessEqualCompare ]: 'less-equal',
  23553. [ GreaterCompare ]: 'greater',
  23554. [ GreaterEqualCompare ]: 'greater-equal',
  23555. [ AlwaysCompare ]: 'always',
  23556. [ NotEqualCompare ]: 'not-equal'
  23557. };
  23558. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  23559. class WebGPUTextureUtils {
  23560. constructor( backend ) {
  23561. this.backend = backend;
  23562. this._passUtils = null;
  23563. this.defaultTexture = {};
  23564. this.defaultCubeTexture = {};
  23565. this.defaultVideoFrame = null;
  23566. this.colorBuffer = null;
  23567. this.depthTexture = new DepthTexture();
  23568. this.depthTexture.name = 'depthBuffer';
  23569. }
  23570. createSampler( texture ) {
  23571. const backend = this.backend;
  23572. const device = backend.device;
  23573. const textureGPU = backend.get( texture );
  23574. const samplerDescriptorGPU = {
  23575. addressModeU: this._convertAddressMode( texture.wrapS ),
  23576. addressModeV: this._convertAddressMode( texture.wrapT ),
  23577. addressModeW: this._convertAddressMode( texture.wrapR ),
  23578. magFilter: this._convertFilterMode( texture.magFilter ),
  23579. minFilter: this._convertFilterMode( texture.minFilter ),
  23580. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  23581. maxAnisotropy: 1
  23582. };
  23583. // anisotropy can only be used when all filter modes are set to linear.
  23584. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  23585. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  23586. }
  23587. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  23588. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  23589. }
  23590. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  23591. }
  23592. createDefaultTexture( texture ) {
  23593. let textureGPU;
  23594. const format = getFormat( texture );
  23595. if ( texture.isCubeTexture ) {
  23596. textureGPU = this._getDefaultCubeTextureGPU( format );
  23597. } else if ( texture.isVideoTexture ) {
  23598. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  23599. } else {
  23600. textureGPU = this._getDefaultTextureGPU( format );
  23601. }
  23602. this.backend.get( texture ).texture = textureGPU;
  23603. }
  23604. createTexture( texture, options = {} ) {
  23605. const backend = this.backend;
  23606. const textureData = backend.get( texture );
  23607. if ( textureData.initialized ) {
  23608. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  23609. }
  23610. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  23611. if ( options.levels === undefined ) options.levels = 1;
  23612. if ( options.depth === undefined ) options.depth = 1;
  23613. const { width, height, depth, levels } = options;
  23614. if ( texture.isFramebufferTexture ) {
  23615. if ( options.renderTarget ) {
  23616. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  23617. } else {
  23618. options.format = this.backend.utils.getPreferredCanvasFormat();
  23619. }
  23620. }
  23621. const dimension = this._getDimension( texture );
  23622. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  23623. textureData.format = format;
  23624. let sampleCount = options.sampleCount !== undefined ? options.sampleCount : 1;
  23625. sampleCount = backend.utils.getSampleCount( sampleCount );
  23626. const primarySampleCount = texture.isRenderTargetTexture && ! texture.isMultisampleRenderTargetTexture ? 1 : sampleCount;
  23627. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  23628. if ( texture.isStorageTexture === true ) {
  23629. usage |= GPUTextureUsage.STORAGE_BINDING;
  23630. }
  23631. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  23632. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  23633. }
  23634. const textureDescriptorGPU = {
  23635. label: texture.name,
  23636. size: {
  23637. width: width,
  23638. height: height,
  23639. depthOrArrayLayers: depth,
  23640. },
  23641. mipLevelCount: levels,
  23642. sampleCount: primarySampleCount,
  23643. dimension: dimension,
  23644. format: format,
  23645. usage: usage
  23646. };
  23647. // texture creation
  23648. if ( texture.isVideoTexture ) {
  23649. const video = texture.source.data;
  23650. const videoFrame = new VideoFrame( video );
  23651. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  23652. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  23653. videoFrame.close();
  23654. textureData.externalTexture = video;
  23655. } else {
  23656. if ( format === undefined ) {
  23657. console.warn( 'WebGPURenderer: Texture format not supported.' );
  23658. return this.createDefaultTexture( texture );
  23659. }
  23660. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  23661. }
  23662. if ( texture.isRenderTargetTexture && sampleCount > 1 && ! texture.isMultisampleRenderTargetTexture ) {
  23663. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  23664. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  23665. msaaTextureDescriptorGPU.sampleCount = sampleCount;
  23666. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  23667. }
  23668. textureData.initialized = true;
  23669. textureData.textureDescriptorGPU = textureDescriptorGPU;
  23670. }
  23671. destroyTexture( texture ) {
  23672. const backend = this.backend;
  23673. const textureData = backend.get( texture );
  23674. if ( textureData.texture !== undefined ) textureData.texture.destroy();
  23675. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  23676. backend.delete( texture );
  23677. }
  23678. destroySampler( texture ) {
  23679. const backend = this.backend;
  23680. const textureData = backend.get( texture );
  23681. delete textureData.sampler;
  23682. }
  23683. generateMipmaps( texture ) {
  23684. const textureData = this.backend.get( texture );
  23685. if ( texture.isCubeTexture ) {
  23686. for ( let i = 0; i < 6; i ++ ) {
  23687. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  23688. }
  23689. } else {
  23690. const depth = texture.image.depth || 1;
  23691. for ( let i = 0; i < depth; i ++ ) {
  23692. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  23693. }
  23694. }
  23695. }
  23696. getColorBuffer() {
  23697. if ( this.colorBuffer ) this.colorBuffer.destroy();
  23698. const backend = this.backend;
  23699. const { width, height } = backend.getDrawingBufferSize();
  23700. this.colorBuffer = backend.device.createTexture( {
  23701. label: 'colorBuffer',
  23702. size: {
  23703. width: width,
  23704. height: height,
  23705. depthOrArrayLayers: 1
  23706. },
  23707. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  23708. format: backend.utils.getPreferredCanvasFormat(),
  23709. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  23710. } );
  23711. return this.colorBuffer;
  23712. }
  23713. getDepthBuffer( depth = true, stencil = false ) {
  23714. const backend = this.backend;
  23715. const { width, height } = backend.getDrawingBufferSize();
  23716. const depthTexture = this.depthTexture;
  23717. const depthTextureGPU = backend.get( depthTexture ).texture;
  23718. let format, type;
  23719. if ( stencil ) {
  23720. format = DepthStencilFormat;
  23721. type = UnsignedInt248Type;
  23722. } else if ( depth ) {
  23723. format = DepthFormat;
  23724. type = UnsignedIntType;
  23725. }
  23726. if ( depthTextureGPU !== undefined ) {
  23727. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  23728. return depthTextureGPU;
  23729. }
  23730. this.destroyTexture( depthTexture );
  23731. }
  23732. depthTexture.name = 'depthBuffer';
  23733. depthTexture.format = format;
  23734. depthTexture.type = type;
  23735. depthTexture.image.width = width;
  23736. depthTexture.image.height = height;
  23737. this.createTexture( depthTexture, { sampleCount: backend.utils.getSampleCount( backend.renderer.samples ), width, height } );
  23738. return backend.get( depthTexture ).texture;
  23739. }
  23740. updateTexture( texture, options ) {
  23741. const textureData = this.backend.get( texture );
  23742. const { textureDescriptorGPU } = textureData;
  23743. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  23744. return;
  23745. // transfer texture data
  23746. if ( texture.isDataTexture ) {
  23747. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  23748. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  23749. for ( let i = 0; i < options.image.depth; i ++ ) {
  23750. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  23751. }
  23752. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  23753. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  23754. } else if ( texture.isCubeTexture ) {
  23755. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  23756. } else if ( texture.isVideoTexture ) {
  23757. const video = texture.source.data;
  23758. textureData.externalTexture = video;
  23759. } else {
  23760. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  23761. }
  23762. //
  23763. textureData.version = texture.version;
  23764. if ( texture.onUpdate ) texture.onUpdate( texture );
  23765. }
  23766. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  23767. const device = this.backend.device;
  23768. const textureData = this.backend.get( texture );
  23769. const textureGPU = textureData.texture;
  23770. const format = textureData.textureDescriptorGPU.format;
  23771. const bytesPerTexel = this._getBytesPerTexel( format );
  23772. let bytesPerRow = width * bytesPerTexel;
  23773. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  23774. const readBuffer = device.createBuffer(
  23775. {
  23776. size: width * height * bytesPerTexel,
  23777. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  23778. }
  23779. );
  23780. const encoder = device.createCommandEncoder();
  23781. encoder.copyTextureToBuffer(
  23782. {
  23783. texture: textureGPU,
  23784. origin: { x, y, z: faceIndex },
  23785. },
  23786. {
  23787. buffer: readBuffer,
  23788. bytesPerRow: bytesPerRow
  23789. },
  23790. {
  23791. width: width,
  23792. height: height
  23793. }
  23794. );
  23795. const typedArrayType = this._getTypedArrayType( format );
  23796. device.queue.submit( [ encoder.finish() ] );
  23797. await readBuffer.mapAsync( GPUMapMode.READ );
  23798. const buffer = readBuffer.getMappedRange();
  23799. return new typedArrayType( buffer );
  23800. }
  23801. _isEnvironmentTexture( texture ) {
  23802. const mapping = texture.mapping;
  23803. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  23804. }
  23805. _getDefaultTextureGPU( format ) {
  23806. let defaultTexture = this.defaultTexture[ format ];
  23807. if ( defaultTexture === undefined ) {
  23808. const texture = new Texture();
  23809. texture.minFilter = NearestFilter;
  23810. texture.magFilter = NearestFilter;
  23811. this.createTexture( texture, { width: 1, height: 1, format } );
  23812. this.defaultTexture[ format ] = defaultTexture = texture;
  23813. }
  23814. return this.backend.get( defaultTexture ).texture;
  23815. }
  23816. _getDefaultCubeTextureGPU( format ) {
  23817. let defaultCubeTexture = this.defaultTexture[ format ];
  23818. if ( defaultCubeTexture === undefined ) {
  23819. const texture = new CubeTexture();
  23820. texture.minFilter = NearestFilter;
  23821. texture.magFilter = NearestFilter;
  23822. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  23823. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  23824. }
  23825. return this.backend.get( defaultCubeTexture ).texture;
  23826. }
  23827. _getDefaultVideoFrame() {
  23828. let defaultVideoFrame = this.defaultVideoFrame;
  23829. if ( defaultVideoFrame === null ) {
  23830. const init = {
  23831. timestamp: 0,
  23832. codedWidth: 1,
  23833. codedHeight: 1,
  23834. format: 'RGBA',
  23835. };
  23836. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  23837. }
  23838. return defaultVideoFrame;
  23839. }
  23840. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  23841. for ( let i = 0; i < 6; i ++ ) {
  23842. const image = images[ i ];
  23843. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  23844. if ( image.isDataTexture ) {
  23845. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  23846. } else {
  23847. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  23848. }
  23849. }
  23850. }
  23851. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  23852. const device = this.backend.device;
  23853. device.queue.copyExternalImageToTexture(
  23854. {
  23855. source: image
  23856. }, {
  23857. texture: textureGPU,
  23858. mipLevel: 0,
  23859. origin: { x: 0, y: 0, z: originDepth }
  23860. }, {
  23861. width: image.width,
  23862. height: image.height,
  23863. depthOrArrayLayers: 1
  23864. }
  23865. );
  23866. if ( flipY === true ) {
  23867. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  23868. }
  23869. }
  23870. _getPassUtils() {
  23871. let passUtils = this._passUtils;
  23872. if ( passUtils === null ) {
  23873. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  23874. }
  23875. return passUtils;
  23876. }
  23877. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  23878. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  23879. }
  23880. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  23881. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  23882. }
  23883. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  23884. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  23885. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  23886. const device = this.backend.device;
  23887. const data = image.data;
  23888. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  23889. const bytesPerRow = image.width * bytesPerTexel;
  23890. device.queue.writeTexture(
  23891. {
  23892. texture: textureGPU,
  23893. mipLevel: 0,
  23894. origin: { x: 0, y: 0, z: originDepth }
  23895. },
  23896. data,
  23897. {
  23898. offset: image.width * image.height * bytesPerTexel * depth,
  23899. bytesPerRow
  23900. },
  23901. {
  23902. width: image.width,
  23903. height: image.height,
  23904. depthOrArrayLayers: 1
  23905. } );
  23906. if ( flipY === true ) {
  23907. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  23908. }
  23909. }
  23910. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  23911. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  23912. const device = this.backend.device;
  23913. const blockData = this._getBlockData( textureDescriptorGPU.format );
  23914. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  23915. for ( let i = 0; i < mipmaps.length; i ++ ) {
  23916. const mipmap = mipmaps[ i ];
  23917. const width = mipmap.width;
  23918. const height = mipmap.height;
  23919. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  23920. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  23921. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  23922. for ( let j = 0; j < depth; j ++ ) {
  23923. device.queue.writeTexture(
  23924. {
  23925. texture: textureGPU,
  23926. mipLevel: i,
  23927. origin: { x: 0, y: 0, z: j }
  23928. },
  23929. mipmap.data,
  23930. {
  23931. offset: j * bytesPerImage,
  23932. bytesPerRow,
  23933. rowsPerImage: Math.ceil( height / blockData.height )
  23934. },
  23935. {
  23936. width: Math.ceil( width / blockData.width ) * blockData.width,
  23937. height: Math.ceil( height / blockData.height ) * blockData.height,
  23938. depthOrArrayLayers: 1
  23939. }
  23940. );
  23941. }
  23942. }
  23943. }
  23944. _getBlockData( format ) {
  23945. // this method is only relevant for compressed texture formats
  23946. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  23947. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  23948. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  23949. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  23950. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  23951. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  23952. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  23953. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  23954. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  23955. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  23956. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  23957. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  23958. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  23959. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  23960. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  23961. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  23962. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  23963. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  23964. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  23965. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  23966. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  23967. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  23968. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  23969. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  23970. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  23971. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  23972. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  23973. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  23974. }
  23975. _convertAddressMode( value ) {
  23976. let addressMode = GPUAddressMode.ClampToEdge;
  23977. if ( value === RepeatWrapping ) {
  23978. addressMode = GPUAddressMode.Repeat;
  23979. } else if ( value === MirroredRepeatWrapping ) {
  23980. addressMode = GPUAddressMode.MirrorRepeat;
  23981. }
  23982. return addressMode;
  23983. }
  23984. _convertFilterMode( value ) {
  23985. let filterMode = GPUFilterMode.Linear;
  23986. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  23987. filterMode = GPUFilterMode.Nearest;
  23988. }
  23989. return filterMode;
  23990. }
  23991. _getBytesPerTexel( format ) {
  23992. // 8-bit formats
  23993. if ( format === GPUTextureFormat.R8Unorm ||
  23994. format === GPUTextureFormat.R8Snorm ||
  23995. format === GPUTextureFormat.R8Uint ||
  23996. format === GPUTextureFormat.R8Sint ) return 1;
  23997. // 16-bit formats
  23998. if ( format === GPUTextureFormat.R16Uint ||
  23999. format === GPUTextureFormat.R16Sint ||
  24000. format === GPUTextureFormat.R16Float ||
  24001. format === GPUTextureFormat.RG8Unorm ||
  24002. format === GPUTextureFormat.RG8Snorm ||
  24003. format === GPUTextureFormat.RG8Uint ||
  24004. format === GPUTextureFormat.RG8Sint ) return 2;
  24005. // 32-bit formats
  24006. if ( format === GPUTextureFormat.R32Uint ||
  24007. format === GPUTextureFormat.R32Sint ||
  24008. format === GPUTextureFormat.R32Float ||
  24009. format === GPUTextureFormat.RG16Uint ||
  24010. format === GPUTextureFormat.RG16Sint ||
  24011. format === GPUTextureFormat.RG16Float ||
  24012. format === GPUTextureFormat.RGBA8Unorm ||
  24013. format === GPUTextureFormat.RGBA8UnormSRGB ||
  24014. format === GPUTextureFormat.RGBA8Snorm ||
  24015. format === GPUTextureFormat.RGBA8Uint ||
  24016. format === GPUTextureFormat.RGBA8Sint ||
  24017. format === GPUTextureFormat.BGRA8Unorm ||
  24018. format === GPUTextureFormat.BGRA8UnormSRGB ||
  24019. // Packed 32-bit formats
  24020. format === GPUTextureFormat.RGB9E5UFloat ||
  24021. format === GPUTextureFormat.RGB10A2Unorm ||
  24022. format === GPUTextureFormat.RG11B10UFloat ||
  24023. format === GPUTextureFormat.Depth32Float ||
  24024. format === GPUTextureFormat.Depth24Plus ||
  24025. format === GPUTextureFormat.Depth24PlusStencil8 ||
  24026. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  24027. // 64-bit formats
  24028. if ( format === GPUTextureFormat.RG32Uint ||
  24029. format === GPUTextureFormat.RG32Sint ||
  24030. format === GPUTextureFormat.RG32Float ||
  24031. format === GPUTextureFormat.RGBA16Uint ||
  24032. format === GPUTextureFormat.RGBA16Sint ||
  24033. format === GPUTextureFormat.RGBA16Float ) return 8;
  24034. // 128-bit formats
  24035. if ( format === GPUTextureFormat.RGBA32Uint ||
  24036. format === GPUTextureFormat.RGBA32Sint ||
  24037. format === GPUTextureFormat.RGBA32Float ) return 16;
  24038. }
  24039. _getTypedArrayType( format ) {
  24040. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  24041. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  24042. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  24043. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  24044. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  24045. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  24046. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  24047. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  24048. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  24049. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  24050. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  24051. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  24052. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  24053. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  24054. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  24055. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  24056. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  24057. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  24058. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  24059. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  24060. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  24061. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  24062. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  24063. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  24064. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  24065. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  24066. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  24067. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  24068. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  24069. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  24070. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  24071. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  24072. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  24073. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  24074. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  24075. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  24076. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  24077. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  24078. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  24079. }
  24080. _getDimension( texture ) {
  24081. let dimension;
  24082. if ( texture.isData3DTexture ) {
  24083. dimension = GPUTextureDimension.ThreeD;
  24084. } else {
  24085. dimension = GPUTextureDimension.TwoD;
  24086. }
  24087. return dimension;
  24088. }
  24089. }
  24090. function getFormat( texture, device = null ) {
  24091. const format = texture.format;
  24092. const type = texture.type;
  24093. const colorSpace = texture.colorSpace;
  24094. let formatGPU;
  24095. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  24096. switch ( format ) {
  24097. case RGBA_S3TC_DXT1_Format:
  24098. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  24099. break;
  24100. case RGBA_S3TC_DXT3_Format:
  24101. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  24102. break;
  24103. case RGBA_S3TC_DXT5_Format:
  24104. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  24105. break;
  24106. case RGB_ETC2_Format:
  24107. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  24108. break;
  24109. case RGBA_ETC2_EAC_Format:
  24110. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  24111. break;
  24112. case RGBA_ASTC_4x4_Format:
  24113. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  24114. break;
  24115. case RGBA_ASTC_5x4_Format:
  24116. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  24117. break;
  24118. case RGBA_ASTC_5x5_Format:
  24119. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  24120. break;
  24121. case RGBA_ASTC_6x5_Format:
  24122. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  24123. break;
  24124. case RGBA_ASTC_6x6_Format:
  24125. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  24126. break;
  24127. case RGBA_ASTC_8x5_Format:
  24128. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  24129. break;
  24130. case RGBA_ASTC_8x6_Format:
  24131. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  24132. break;
  24133. case RGBA_ASTC_8x8_Format:
  24134. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  24135. break;
  24136. case RGBA_ASTC_10x5_Format:
  24137. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  24138. break;
  24139. case RGBA_ASTC_10x6_Format:
  24140. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  24141. break;
  24142. case RGBA_ASTC_10x8_Format:
  24143. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  24144. break;
  24145. case RGBA_ASTC_10x10_Format:
  24146. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  24147. break;
  24148. case RGBA_ASTC_12x10_Format:
  24149. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  24150. break;
  24151. case RGBA_ASTC_12x12_Format:
  24152. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  24153. break;
  24154. case RGBAFormat:
  24155. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  24156. break;
  24157. default:
  24158. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  24159. }
  24160. } else {
  24161. switch ( format ) {
  24162. case RGBAFormat:
  24163. switch ( type ) {
  24164. case ByteType:
  24165. formatGPU = GPUTextureFormat.RGBA8Snorm;
  24166. break;
  24167. case ShortType:
  24168. formatGPU = GPUTextureFormat.RGBA16Sint;
  24169. break;
  24170. case UnsignedShortType:
  24171. formatGPU = GPUTextureFormat.RGBA16Uint;
  24172. break;
  24173. case UnsignedIntType:
  24174. formatGPU = GPUTextureFormat.RGBA32Uint;
  24175. break;
  24176. case IntType:
  24177. formatGPU = GPUTextureFormat.RGBA32Sint;
  24178. break;
  24179. case UnsignedByteType:
  24180. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  24181. break;
  24182. case HalfFloatType:
  24183. formatGPU = GPUTextureFormat.RGBA16Float;
  24184. break;
  24185. case FloatType:
  24186. formatGPU = GPUTextureFormat.RGBA32Float;
  24187. break;
  24188. default:
  24189. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  24190. }
  24191. break;
  24192. case RGBFormat:
  24193. switch ( type ) {
  24194. case UnsignedInt5999Type:
  24195. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  24196. break;
  24197. default:
  24198. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  24199. }
  24200. break;
  24201. case RedFormat:
  24202. switch ( type ) {
  24203. case ByteType:
  24204. formatGPU = GPUTextureFormat.R8Snorm;
  24205. break;
  24206. case ShortType:
  24207. formatGPU = GPUTextureFormat.R16Sint;
  24208. break;
  24209. case UnsignedShortType:
  24210. formatGPU = GPUTextureFormat.R16Uint;
  24211. break;
  24212. case UnsignedIntType:
  24213. formatGPU = GPUTextureFormat.R32Uint;
  24214. break;
  24215. case IntType:
  24216. formatGPU = GPUTextureFormat.R32Sint;
  24217. break;
  24218. case UnsignedByteType:
  24219. formatGPU = GPUTextureFormat.R8Unorm;
  24220. break;
  24221. case HalfFloatType:
  24222. formatGPU = GPUTextureFormat.R16Float;
  24223. break;
  24224. case FloatType:
  24225. formatGPU = GPUTextureFormat.R32Float;
  24226. break;
  24227. default:
  24228. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  24229. }
  24230. break;
  24231. case RGFormat:
  24232. switch ( type ) {
  24233. case ByteType:
  24234. formatGPU = GPUTextureFormat.RG8Snorm;
  24235. break;
  24236. case ShortType:
  24237. formatGPU = GPUTextureFormat.RG16Sint;
  24238. break;
  24239. case UnsignedShortType:
  24240. formatGPU = GPUTextureFormat.RG16Uint;
  24241. break;
  24242. case UnsignedIntType:
  24243. formatGPU = GPUTextureFormat.RG32Uint;
  24244. break;
  24245. case IntType:
  24246. formatGPU = GPUTextureFormat.RG32Sint;
  24247. break;
  24248. case UnsignedByteType:
  24249. formatGPU = GPUTextureFormat.RG8Unorm;
  24250. break;
  24251. case HalfFloatType:
  24252. formatGPU = GPUTextureFormat.RG16Float;
  24253. break;
  24254. case FloatType:
  24255. formatGPU = GPUTextureFormat.RG32Float;
  24256. break;
  24257. default:
  24258. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  24259. }
  24260. break;
  24261. case DepthFormat:
  24262. switch ( type ) {
  24263. case UnsignedShortType:
  24264. formatGPU = GPUTextureFormat.Depth16Unorm;
  24265. break;
  24266. case UnsignedIntType:
  24267. formatGPU = GPUTextureFormat.Depth24Plus;
  24268. break;
  24269. case FloatType:
  24270. formatGPU = GPUTextureFormat.Depth32Float;
  24271. break;
  24272. default:
  24273. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  24274. }
  24275. break;
  24276. case DepthStencilFormat:
  24277. switch ( type ) {
  24278. case UnsignedInt248Type:
  24279. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  24280. break;
  24281. case FloatType:
  24282. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  24283. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  24284. }
  24285. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  24286. break;
  24287. default:
  24288. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  24289. }
  24290. break;
  24291. case RedIntegerFormat:
  24292. switch ( type ) {
  24293. case IntType:
  24294. formatGPU = GPUTextureFormat.R32Sint;
  24295. break;
  24296. case UnsignedIntType:
  24297. formatGPU = GPUTextureFormat.R32Uint;
  24298. break;
  24299. default:
  24300. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  24301. }
  24302. break;
  24303. case RGIntegerFormat:
  24304. switch ( type ) {
  24305. case IntType:
  24306. formatGPU = GPUTextureFormat.RG32Sint;
  24307. break;
  24308. case UnsignedIntType:
  24309. formatGPU = GPUTextureFormat.RG32Uint;
  24310. break;
  24311. default:
  24312. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  24313. }
  24314. break;
  24315. case RGBAIntegerFormat:
  24316. switch ( type ) {
  24317. case IntType:
  24318. formatGPU = GPUTextureFormat.RGBA32Sint;
  24319. break;
  24320. case UnsignedIntType:
  24321. formatGPU = GPUTextureFormat.RGBA32Uint;
  24322. break;
  24323. default:
  24324. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  24325. }
  24326. break;
  24327. default:
  24328. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  24329. }
  24330. }
  24331. return formatGPU;
  24332. }
  24333. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  24334. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  24335. const wgslTypeLib$1 = {
  24336. 'f32': 'float',
  24337. 'i32': 'int',
  24338. 'u32': 'uint',
  24339. 'bool': 'bool',
  24340. 'vec2<f32>': 'vec2',
  24341. 'vec2<i32>': 'ivec2',
  24342. 'vec2<u32>': 'uvec2',
  24343. 'vec2<bool>': 'bvec2',
  24344. 'vec2f': 'vec2',
  24345. 'vec2i': 'ivec2',
  24346. 'vec2u': 'uvec2',
  24347. 'vec2b': 'bvec2',
  24348. 'vec3<f32>': 'vec3',
  24349. 'vec3<i32>': 'ivec3',
  24350. 'vec3<u32>': 'uvec3',
  24351. 'vec3<bool>': 'bvec3',
  24352. 'vec3f': 'vec3',
  24353. 'vec3i': 'ivec3',
  24354. 'vec3u': 'uvec3',
  24355. 'vec3b': 'bvec3',
  24356. 'vec4<f32>': 'vec4',
  24357. 'vec4<i32>': 'ivec4',
  24358. 'vec4<u32>': 'uvec4',
  24359. 'vec4<bool>': 'bvec4',
  24360. 'vec4f': 'vec4',
  24361. 'vec4i': 'ivec4',
  24362. 'vec4u': 'uvec4',
  24363. 'vec4b': 'bvec4',
  24364. 'mat2x2<f32>': 'mat2',
  24365. 'mat2x2f': 'mat2',
  24366. 'mat3x3<f32>': 'mat3',
  24367. 'mat3x3f': 'mat3',
  24368. 'mat4x4<f32>': 'mat4',
  24369. 'mat4x4f': 'mat4',
  24370. 'sampler': 'sampler',
  24371. 'texture_1d': 'texture',
  24372. 'texture_2d': 'texture',
  24373. 'texture_2d_array': 'texture',
  24374. 'texture_multisampled_2d': 'cubeTexture',
  24375. 'texture_depth_2d': 'depthTexture',
  24376. 'texture_3d': 'texture3D',
  24377. 'texture_cube': 'cubeTexture',
  24378. 'texture_cube_array': 'cubeTexture',
  24379. 'texture_storage_1d': 'storageTexture',
  24380. 'texture_storage_2d': 'storageTexture',
  24381. 'texture_storage_2d_array': 'storageTexture',
  24382. 'texture_storage_3d': 'storageTexture'
  24383. };
  24384. const parse = ( source ) => {
  24385. source = source.trim();
  24386. const declaration = source.match( declarationRegexp );
  24387. if ( declaration !== null && declaration.length === 4 ) {
  24388. const inputsCode = declaration[ 2 ];
  24389. const propsMatches = [];
  24390. let match = null;
  24391. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  24392. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  24393. }
  24394. // Process matches to correctly pair names and types
  24395. const inputs = [];
  24396. for ( let i = 0; i < propsMatches.length; i ++ ) {
  24397. const { name, type } = propsMatches[ i ];
  24398. let resolvedType = type;
  24399. if ( resolvedType.startsWith( 'ptr' ) ) {
  24400. resolvedType = 'pointer';
  24401. } else {
  24402. if ( resolvedType.startsWith( 'texture' ) ) {
  24403. resolvedType = type.split( '<' )[ 0 ];
  24404. }
  24405. resolvedType = wgslTypeLib$1[ resolvedType ];
  24406. }
  24407. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  24408. }
  24409. const blockCode = source.substring( declaration[ 0 ].length );
  24410. const outputType = declaration[ 3 ] || 'void';
  24411. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  24412. const type = wgslTypeLib$1[ outputType ] || outputType;
  24413. return {
  24414. type,
  24415. inputs,
  24416. name,
  24417. inputsCode,
  24418. blockCode,
  24419. outputType
  24420. };
  24421. } else {
  24422. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  24423. }
  24424. };
  24425. /**
  24426. * This class represents a WSL node function.
  24427. *
  24428. * @augments NodeFunction
  24429. */
  24430. class WGSLNodeFunction extends NodeFunction {
  24431. /**
  24432. * Constructs a new WGSL node function.
  24433. *
  24434. * @param {String} source - The WGSL source.
  24435. */
  24436. constructor( source ) {
  24437. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  24438. super( type, inputs, name );
  24439. this.inputsCode = inputsCode;
  24440. this.blockCode = blockCode;
  24441. this.outputType = outputType;
  24442. }
  24443. /**
  24444. * This method returns the WGSL code of the node function.
  24445. *
  24446. * @param {String} [name=this.name] - The function's name.
  24447. * @return {String} The shader code.
  24448. */
  24449. getCode( name = this.name ) {
  24450. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  24451. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  24452. }
  24453. }
  24454. /**
  24455. * A WGSL node parser.
  24456. *
  24457. * @augments NodeParser
  24458. */
  24459. class WGSLNodeParser extends NodeParser {
  24460. /**
  24461. * The method parses the given WGSL code an returns a node function.
  24462. *
  24463. * @param {String} source - The WGSL code.
  24464. * @return {WGSLNodeFunction} A node function.
  24465. */
  24466. parseFunction( source ) {
  24467. return new WGSLNodeFunction( source );
  24468. }
  24469. }
  24470. // GPUShaderStage is not defined in browsers not supporting WebGPU
  24471. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  24472. const accessNames = {
  24473. [ NodeAccess.READ_ONLY ]: 'read',
  24474. [ NodeAccess.WRITE_ONLY ]: 'write',
  24475. [ NodeAccess.READ_WRITE ]: 'read_write'
  24476. };
  24477. const wrapNames = {
  24478. [ RepeatWrapping ]: 'repeat',
  24479. [ ClampToEdgeWrapping ]: 'clamp',
  24480. [ MirroredRepeatWrapping ]: 'mirror'
  24481. };
  24482. const gpuShaderStageLib = {
  24483. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  24484. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  24485. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  24486. };
  24487. const supports = {
  24488. instance: true,
  24489. swizzleAssign: false,
  24490. storageBuffer: true
  24491. };
  24492. const wgslFnOpLib = {
  24493. '^^': 'tsl_xor'
  24494. };
  24495. const wgslTypeLib = {
  24496. float: 'f32',
  24497. int: 'i32',
  24498. uint: 'u32',
  24499. bool: 'bool',
  24500. color: 'vec3<f32>',
  24501. vec2: 'vec2<f32>',
  24502. ivec2: 'vec2<i32>',
  24503. uvec2: 'vec2<u32>',
  24504. bvec2: 'vec2<bool>',
  24505. vec3: 'vec3<f32>',
  24506. ivec3: 'vec3<i32>',
  24507. uvec3: 'vec3<u32>',
  24508. bvec3: 'vec3<bool>',
  24509. vec4: 'vec4<f32>',
  24510. ivec4: 'vec4<i32>',
  24511. uvec4: 'vec4<u32>',
  24512. bvec4: 'vec4<bool>',
  24513. mat2: 'mat2x2<f32>',
  24514. mat3: 'mat3x3<f32>',
  24515. mat4: 'mat4x4<f32>'
  24516. };
  24517. const wgslCodeCache = {};
  24518. const wgslPolyfill = {
  24519. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  24520. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  24521. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  24522. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  24523. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  24524. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  24525. 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 ); }' ),
  24526. 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 ); }' ),
  24527. 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 ); }' ),
  24528. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  24529. mirrorWrapping_float: new CodeNode( 'fn tsl_mirrorWrapping_float( coord: f32 ) -> f32 { let mirrored = fract( coord * 0.5 ) * 2.0; return 1.0 - abs( 1.0 - mirrored ); }' ),
  24530. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  24531. biquadraticTexture: new CodeNode( /* wgsl */`
  24532. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  24533. let res = vec2f( iRes );
  24534. let uvScaled = coord * res;
  24535. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  24536. // https://www.shadertoy.com/view/WtyXRy
  24537. let uv = uvWrapping - 0.5;
  24538. let iuv = floor( uv );
  24539. let f = fract( uv );
  24540. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  24541. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  24542. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  24543. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  24544. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  24545. }
  24546. ` )
  24547. };
  24548. const wgslMethods = {
  24549. dFdx: 'dpdx',
  24550. dFdy: '- dpdy',
  24551. mod_float: 'tsl_mod_float',
  24552. mod_vec2: 'tsl_mod_vec2',
  24553. mod_vec3: 'tsl_mod_vec3',
  24554. mod_vec4: 'tsl_mod_vec4',
  24555. equals_bool: 'tsl_equals_bool',
  24556. equals_bvec2: 'tsl_equals_bvec2',
  24557. equals_bvec3: 'tsl_equals_bvec3',
  24558. equals_bvec4: 'tsl_equals_bvec4',
  24559. inversesqrt: 'inverseSqrt',
  24560. bitcast: 'bitcast<f32>'
  24561. };
  24562. // WebGPU issue: does not support pow() with negative base on Windows
  24563. if ( typeof navigator !== 'undefined' && /Windows/g.test( navigator.userAgent ) ) {
  24564. 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 ); }' );
  24565. 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 ] );
  24566. 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 ] );
  24567. 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 ] );
  24568. wgslMethods.pow_float = 'tsl_pow_float';
  24569. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  24570. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  24571. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  24572. }
  24573. //
  24574. let diagnostics = '';
  24575. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  24576. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  24577. }
  24578. //
  24579. class WGSLNodeBuilder extends NodeBuilder {
  24580. constructor( object, renderer ) {
  24581. super( object, renderer, new WGSLNodeParser() );
  24582. this.uniformGroups = {};
  24583. this.builtins = {};
  24584. this.directives = {};
  24585. this.scopedArrays = new Map();
  24586. }
  24587. needsToWorkingColorSpace( texture ) {
  24588. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  24589. }
  24590. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  24591. if ( shaderStage === 'fragment' ) {
  24592. if ( depthSnippet ) {
  24593. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  24594. } else {
  24595. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  24596. }
  24597. } else if ( this.isFilteredTexture( texture ) ) {
  24598. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  24599. } else {
  24600. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0' );
  24601. }
  24602. }
  24603. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  24604. if ( shaderStage === 'fragment' ) {
  24605. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  24606. } else {
  24607. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  24608. }
  24609. }
  24610. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  24611. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false ) {
  24612. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  24613. } else if ( this.isFilteredTexture( texture ) ) {
  24614. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  24615. } else {
  24616. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  24617. }
  24618. }
  24619. generateWrapFunction( texture ) {
  24620. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }T`;
  24621. let nodeCode = wgslCodeCache[ functionName ];
  24622. if ( nodeCode === undefined ) {
  24623. const includes = [];
  24624. let code = `fn ${ functionName }( coord : vec2f ) -> vec2f {\n\n\treturn vec2f(\n`;
  24625. const addWrapSnippet = ( wrap, axis ) => {
  24626. if ( wrap === RepeatWrapping ) {
  24627. includes.push( wgslPolyfill.repeatWrapping_float );
  24628. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  24629. } else if ( wrap === ClampToEdgeWrapping ) {
  24630. includes.push( wgslPolyfill.clampWrapping_float );
  24631. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  24632. } else if ( wrap === MirroredRepeatWrapping ) {
  24633. includes.push( wgslPolyfill.mirrorWrapping_float );
  24634. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  24635. } else {
  24636. code += `\t\tcoord.${ axis }`;
  24637. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  24638. }
  24639. };
  24640. addWrapSnippet( texture.wrapS, 'x' );
  24641. code += ',\n';
  24642. addWrapSnippet( texture.wrapT, 'y' );
  24643. code += '\n\t);\n\n}\n';
  24644. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  24645. }
  24646. nodeCode.build( this );
  24647. return functionName;
  24648. }
  24649. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  24650. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  24651. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  24652. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  24653. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  24654. let textureDimensionsParams;
  24655. if ( texture.isMultisampleRenderTargetTexture === true ) {
  24656. textureDimensionsParams = textureProperty;
  24657. } else {
  24658. textureDimensionsParams = `${ textureProperty }, u32( ${ levelSnippet } )`;
  24659. }
  24660. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, 'uvec2' ) );
  24661. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  24662. }
  24663. return textureDimensionNode.build( this );
  24664. }
  24665. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  24666. this._include( 'biquadraticTexture' );
  24667. const wrapFunction = this.generateWrapFunction( texture );
  24668. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  24669. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  24670. }
  24671. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  24672. const wrapFunction = this.generateWrapFunction( texture );
  24673. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  24674. const coordSnippet = `vec2u( ${ wrapFunction }( ${ uvSnippet } ) * vec2f( ${ textureDimension } ) )`;
  24675. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  24676. }
  24677. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  24678. if ( texture.isVideoTexture === true || texture.isStorageTexture === true ) {
  24679. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet } )`;
  24680. } else if ( depthSnippet ) {
  24681. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  24682. } else {
  24683. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  24684. }
  24685. }
  24686. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  24687. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  24688. }
  24689. isSampleCompare( texture ) {
  24690. return texture.isDepthTexture === true && texture.compareFunction !== null;
  24691. }
  24692. isUnfilterable( texture ) {
  24693. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  24694. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  24695. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  24696. texture.isMultisampleRenderTargetTexture === true;
  24697. }
  24698. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  24699. let snippet = null;
  24700. if ( texture.isVideoTexture === true ) {
  24701. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  24702. } else if ( this.isUnfilterable( texture ) ) {
  24703. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  24704. } else {
  24705. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  24706. }
  24707. return snippet;
  24708. }
  24709. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  24710. if ( shaderStage === 'fragment' ) {
  24711. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  24712. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  24713. } else {
  24714. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  24715. }
  24716. }
  24717. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  24718. if ( shaderStage === 'fragment' ) {
  24719. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  24720. } else {
  24721. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  24722. }
  24723. }
  24724. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  24725. let snippet = null;
  24726. if ( texture.isVideoTexture === true ) {
  24727. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  24728. } else {
  24729. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  24730. }
  24731. return snippet;
  24732. }
  24733. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  24734. if ( shaderStage === 'fragment' ) {
  24735. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  24736. } else {
  24737. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  24738. }
  24739. }
  24740. getPropertyName( node, shaderStage = this.shaderStage ) {
  24741. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  24742. if ( shaderStage === 'vertex' ) {
  24743. return `varyings.${ node.name }`;
  24744. }
  24745. } else if ( node.isNodeUniform === true ) {
  24746. const name = node.name;
  24747. const type = node.type;
  24748. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  24749. return name;
  24750. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  24751. return `NodeBuffer_${ node.id }.${name}`;
  24752. } else {
  24753. return node.groupNode.name + '.' + name;
  24754. }
  24755. }
  24756. return super.getPropertyName( node );
  24757. }
  24758. getOutputStructName() {
  24759. return 'output';
  24760. }
  24761. _getUniformGroupCount( shaderStage ) {
  24762. return Object.keys( this.uniforms[ shaderStage ] ).length;
  24763. }
  24764. getFunctionOperator( op ) {
  24765. const fnOp = wgslFnOpLib[ op ];
  24766. if ( fnOp !== undefined ) {
  24767. this._include( fnOp );
  24768. return fnOp;
  24769. }
  24770. return null;
  24771. }
  24772. getNodeAccess( node, shaderStage ) {
  24773. if ( shaderStage !== 'compute' )
  24774. return NodeAccess.READ_ONLY;
  24775. return node.access;
  24776. }
  24777. getStorageAccess( node, shaderStage ) {
  24778. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  24779. }
  24780. getUniformFromNode( node, type, shaderStage, name = null ) {
  24781. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  24782. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  24783. if ( nodeData.uniformGPU === undefined ) {
  24784. let uniformGPU;
  24785. const group = node.groupNode;
  24786. const groupName = group.name;
  24787. const bindings = this.getBindGroupArray( groupName, shaderStage );
  24788. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  24789. let texture = null;
  24790. const access = this.getNodeAccess( node, shaderStage );
  24791. if ( type === 'texture' || type === 'storageTexture' ) {
  24792. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  24793. } else if ( type === 'cubeTexture' ) {
  24794. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  24795. } else if ( type === 'texture3D' ) {
  24796. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  24797. }
  24798. texture.store = node.isStorageTextureNode === true;
  24799. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  24800. if ( shaderStage === 'fragment' && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  24801. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  24802. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  24803. bindings.push( sampler, texture );
  24804. uniformGPU = [ sampler, texture ];
  24805. } else {
  24806. bindings.push( texture );
  24807. uniformGPU = [ texture ];
  24808. }
  24809. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  24810. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  24811. const buffer = new bufferClass( node, group );
  24812. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  24813. bindings.push( buffer );
  24814. uniformGPU = buffer;
  24815. } else {
  24816. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  24817. let uniformsGroup = uniformsStage[ groupName ];
  24818. if ( uniformsGroup === undefined ) {
  24819. uniformsGroup = new NodeUniformsGroup( groupName, group );
  24820. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  24821. uniformsStage[ groupName ] = uniformsGroup;
  24822. bindings.push( uniformsGroup );
  24823. }
  24824. uniformGPU = this.getNodeUniform( uniformNode, type );
  24825. uniformsGroup.addUniform( uniformGPU );
  24826. }
  24827. nodeData.uniformGPU = uniformGPU;
  24828. }
  24829. return uniformNode;
  24830. }
  24831. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  24832. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  24833. if ( map.has( name ) === false ) {
  24834. map.set( name, {
  24835. name,
  24836. property,
  24837. type
  24838. } );
  24839. }
  24840. return property;
  24841. }
  24842. hasBuiltin( name, shaderStage = this.shaderStage ) {
  24843. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  24844. }
  24845. getVertexIndex() {
  24846. if ( this.shaderStage === 'vertex' ) {
  24847. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  24848. }
  24849. return 'vertexIndex';
  24850. }
  24851. buildFunctionCode( shaderNode ) {
  24852. const layout = shaderNode.layout;
  24853. const flowData = this.flowShaderNode( shaderNode );
  24854. const parameters = [];
  24855. for ( const input of layout.inputs ) {
  24856. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  24857. }
  24858. //
  24859. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  24860. ${ flowData.vars }
  24861. ${ flowData.code }
  24862. `;
  24863. if ( flowData.result ) {
  24864. code += `\treturn ${ flowData.result };\n`;
  24865. }
  24866. code += '\n}\n';
  24867. //
  24868. return code;
  24869. }
  24870. getInstanceIndex() {
  24871. if ( this.shaderStage === 'vertex' ) {
  24872. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  24873. }
  24874. return 'instanceIndex';
  24875. }
  24876. getInvocationLocalIndex() {
  24877. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  24878. }
  24879. getSubgroupSize() {
  24880. this.enableSubGroups();
  24881. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  24882. }
  24883. getInvocationSubgroupIndex() {
  24884. this.enableSubGroups();
  24885. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  24886. }
  24887. getSubgroupIndex() {
  24888. this.enableSubGroups();
  24889. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  24890. }
  24891. getDrawIndex() {
  24892. return null;
  24893. }
  24894. getFrontFacing() {
  24895. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  24896. }
  24897. getFragCoord() {
  24898. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  24899. }
  24900. getFragDepth() {
  24901. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  24902. }
  24903. getClipDistance() {
  24904. return 'varyings.hw_clip_distances';
  24905. }
  24906. isFlipY() {
  24907. return false;
  24908. }
  24909. enableDirective( name, shaderStage = this.shaderStage ) {
  24910. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  24911. stage.add( name );
  24912. }
  24913. getDirectives( shaderStage ) {
  24914. const snippets = [];
  24915. const directives = this.directives[ shaderStage ];
  24916. if ( directives !== undefined ) {
  24917. for ( const directive of directives ) {
  24918. snippets.push( `enable ${directive};` );
  24919. }
  24920. }
  24921. return snippets.join( '\n' );
  24922. }
  24923. enableSubGroups() {
  24924. this.enableDirective( 'subgroups' );
  24925. }
  24926. enableSubgroupsF16() {
  24927. this.enableDirective( 'subgroups-f16' );
  24928. }
  24929. enableClipDistances() {
  24930. this.enableDirective( 'clip_distances' );
  24931. }
  24932. enableShaderF16() {
  24933. this.enableDirective( 'f16' );
  24934. }
  24935. enableDualSourceBlending() {
  24936. this.enableDirective( 'dual_source_blending' );
  24937. }
  24938. enableHardwareClipping( planeCount ) {
  24939. this.enableClipDistances();
  24940. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  24941. }
  24942. getBuiltins( shaderStage ) {
  24943. const snippets = [];
  24944. const builtins = this.builtins[ shaderStage ];
  24945. if ( builtins !== undefined ) {
  24946. for ( const { name, property, type } of builtins.values() ) {
  24947. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  24948. }
  24949. }
  24950. return snippets.join( ',\n\t' );
  24951. }
  24952. getScopedArray( name, scope, bufferType, bufferCount ) {
  24953. if ( this.scopedArrays.has( name ) === false ) {
  24954. this.scopedArrays.set( name, {
  24955. name,
  24956. scope,
  24957. bufferType,
  24958. bufferCount
  24959. } );
  24960. }
  24961. return name;
  24962. }
  24963. getScopedArrays( shaderStage ) {
  24964. if ( shaderStage !== 'compute' ) {
  24965. return;
  24966. }
  24967. const snippets = [];
  24968. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  24969. const type = this.getType( bufferType );
  24970. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  24971. }
  24972. return snippets.join( '\n' );
  24973. }
  24974. getAttributes( shaderStage ) {
  24975. const snippets = [];
  24976. if ( shaderStage === 'compute' ) {
  24977. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  24978. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  24979. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  24980. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  24981. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  24982. this.enableDirective( 'subgroups', shaderStage );
  24983. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  24984. }
  24985. }
  24986. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  24987. const builtins = this.getBuiltins( 'attribute' );
  24988. if ( builtins ) snippets.push( builtins );
  24989. const attributes = this.getAttributesArray();
  24990. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  24991. const attribute = attributes[ index ];
  24992. const name = attribute.name;
  24993. const type = this.getType( attribute.type );
  24994. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  24995. }
  24996. }
  24997. return snippets.join( ',\n\t' );
  24998. }
  24999. getStructMembers( struct ) {
  25000. const snippets = [];
  25001. const members = struct.getMemberTypes();
  25002. for ( let i = 0; i < members.length; i ++ ) {
  25003. const member = members[ i ];
  25004. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  25005. }
  25006. const builtins = this.getBuiltins( 'output' );
  25007. if ( builtins ) snippets.push( '\t' + builtins );
  25008. return snippets.join( ',\n' );
  25009. }
  25010. getStructs( shaderStage ) {
  25011. const snippets = [];
  25012. const structs = this.structs[ shaderStage ];
  25013. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  25014. const struct = structs[ index ];
  25015. const name = struct.name;
  25016. let snippet = `\struct ${ name } {\n`;
  25017. snippet += this.getStructMembers( struct );
  25018. snippet += '\n}';
  25019. snippets.push( snippet );
  25020. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  25021. }
  25022. return snippets.join( '\n\n' );
  25023. }
  25024. getVar( type, name ) {
  25025. return `var ${ name } : ${ this.getType( type ) }`;
  25026. }
  25027. getVars( shaderStage ) {
  25028. const snippets = [];
  25029. const vars = this.vars[ shaderStage ];
  25030. if ( vars !== undefined ) {
  25031. for ( const variable of vars ) {
  25032. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  25033. }
  25034. }
  25035. return `\n${ snippets.join( '\n' ) }\n`;
  25036. }
  25037. getVaryings( shaderStage ) {
  25038. const snippets = [];
  25039. if ( shaderStage === 'vertex' ) {
  25040. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  25041. }
  25042. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  25043. const varyings = this.varyings;
  25044. const vars = this.vars[ shaderStage ];
  25045. for ( let index = 0; index < varyings.length; index ++ ) {
  25046. const varying = varyings[ index ];
  25047. if ( varying.needsInterpolation ) {
  25048. let attributesSnippet = `@location( ${index} )`;
  25049. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  25050. attributesSnippet += ' @interpolate( flat )';
  25051. }
  25052. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  25053. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  25054. vars.push( varying );
  25055. }
  25056. }
  25057. }
  25058. const builtins = this.getBuiltins( shaderStage );
  25059. if ( builtins ) snippets.push( builtins );
  25060. const code = snippets.join( ',\n\t' );
  25061. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  25062. }
  25063. getUniforms( shaderStage ) {
  25064. const uniforms = this.uniforms[ shaderStage ];
  25065. const bindingSnippets = [];
  25066. const bufferSnippets = [];
  25067. const structSnippets = [];
  25068. const uniformGroups = {};
  25069. for ( const uniform of uniforms ) {
  25070. const groupName = uniform.groupNode.name;
  25071. const uniformIndexes = this.bindingsIndexes[ groupName ];
  25072. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  25073. const texture = uniform.node.value;
  25074. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  25075. if ( this.isSampleCompare( texture ) ) {
  25076. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  25077. } else {
  25078. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  25079. }
  25080. }
  25081. let textureType;
  25082. let multisampled = '';
  25083. if ( texture.isMultisampleRenderTargetTexture === true ) {
  25084. multisampled = '_multisampled';
  25085. }
  25086. if ( texture.isCubeTexture === true ) {
  25087. textureType = 'texture_cube<f32>';
  25088. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  25089. textureType = 'texture_2d_array<f32>';
  25090. } else if ( texture.isDepthTexture === true ) {
  25091. textureType = `texture_depth${multisampled}_2d`;
  25092. } else if ( texture.isVideoTexture === true ) {
  25093. textureType = 'texture_external';
  25094. } else if ( texture.isData3DTexture === true ) {
  25095. textureType = 'texture_3d<f32>';
  25096. } else if ( uniform.node.isStorageTextureNode === true ) {
  25097. const format = getFormat( texture );
  25098. const access = this.getStorageAccess( uniform.node, shaderStage );
  25099. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  25100. } else {
  25101. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  25102. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  25103. }
  25104. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  25105. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  25106. const bufferNode = uniform.node;
  25107. const bufferType = this.getType( bufferNode.bufferType );
  25108. const bufferCount = bufferNode.bufferCount;
  25109. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  25110. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${bufferType}>` : `${bufferType}`;
  25111. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >\n`;
  25112. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  25113. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  25114. } else {
  25115. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  25116. const groupName = uniform.groupNode.name;
  25117. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  25118. index: uniformIndexes.binding ++,
  25119. id: uniformIndexes.group,
  25120. snippets: []
  25121. } );
  25122. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  25123. }
  25124. }
  25125. for ( const name in uniformGroups ) {
  25126. const group = uniformGroups[ name ];
  25127. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  25128. }
  25129. let code = bindingSnippets.join( '\n' );
  25130. code += bufferSnippets.join( '\n' );
  25131. code += structSnippets.join( '\n' );
  25132. return code;
  25133. }
  25134. buildCode() {
  25135. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  25136. this.sortBindingGroups();
  25137. for ( const shaderStage in shadersData ) {
  25138. const stageData = shadersData[ shaderStage ];
  25139. stageData.uniforms = this.getUniforms( shaderStage );
  25140. stageData.attributes = this.getAttributes( shaderStage );
  25141. stageData.varyings = this.getVaryings( shaderStage );
  25142. stageData.structs = this.getStructs( shaderStage );
  25143. stageData.vars = this.getVars( shaderStage );
  25144. stageData.codes = this.getCodes( shaderStage );
  25145. stageData.directives = this.getDirectives( shaderStage );
  25146. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  25147. //
  25148. let flow = '// code\n\n';
  25149. flow += this.flowCode[ shaderStage ];
  25150. const flowNodes = this.flowNodes[ shaderStage ];
  25151. const mainNode = flowNodes[ flowNodes.length - 1 ];
  25152. const outputNode = mainNode.outputNode;
  25153. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  25154. for ( const node of flowNodes ) {
  25155. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  25156. const slotName = node.name;
  25157. if ( slotName ) {
  25158. if ( flow.length > 0 ) flow += '\n';
  25159. flow += `\t// flow -> ${ slotName }\n\t`;
  25160. }
  25161. flow += `${ flowSlotData.code }\n\t`;
  25162. if ( node === mainNode && shaderStage !== 'compute' ) {
  25163. flow += '// result\n\n\t';
  25164. if ( shaderStage === 'vertex' ) {
  25165. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  25166. } else if ( shaderStage === 'fragment' ) {
  25167. if ( isOutputStruct ) {
  25168. stageData.returnType = outputNode.nodeType;
  25169. flow += `return ${ flowSlotData.result };`;
  25170. } else {
  25171. let structSnippet = '\t@location(0) color: vec4<f32>';
  25172. const builtins = this.getBuiltins( 'output' );
  25173. if ( builtins ) structSnippet += ',\n\t' + builtins;
  25174. stageData.returnType = 'OutputStruct';
  25175. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  25176. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  25177. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  25178. }
  25179. }
  25180. }
  25181. }
  25182. stageData.flow = flow;
  25183. }
  25184. if ( this.material !== null ) {
  25185. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  25186. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  25187. } else {
  25188. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  25189. }
  25190. }
  25191. getMethod( method, output = null ) {
  25192. let wgslMethod;
  25193. if ( output !== null ) {
  25194. wgslMethod = this._getWGSLMethod( method + '_' + output );
  25195. }
  25196. if ( wgslMethod === undefined ) {
  25197. wgslMethod = this._getWGSLMethod( method );
  25198. }
  25199. return wgslMethod || method;
  25200. }
  25201. getType( type ) {
  25202. return wgslTypeLib[ type ] || type;
  25203. }
  25204. isAvailable( name ) {
  25205. let result = supports[ name ];
  25206. if ( result === undefined ) {
  25207. if ( name === 'float32Filterable' ) {
  25208. result = this.renderer.hasFeature( 'float32-filterable' );
  25209. } else if ( name === 'clipDistance' ) {
  25210. result = this.renderer.hasFeature( 'clip-distances' );
  25211. }
  25212. supports[ name ] = result;
  25213. }
  25214. return result;
  25215. }
  25216. _getWGSLMethod( method ) {
  25217. if ( wgslPolyfill[ method ] !== undefined ) {
  25218. this._include( method );
  25219. }
  25220. return wgslMethods[ method ];
  25221. }
  25222. _include( name ) {
  25223. const codeNode = wgslPolyfill[ name ];
  25224. codeNode.build( this );
  25225. if ( this.currentFunctionNode !== null ) {
  25226. this.currentFunctionNode.includes.push( codeNode );
  25227. }
  25228. return codeNode;
  25229. }
  25230. _getWGSLVertexCode( shaderData ) {
  25231. return `${ this.getSignature() }
  25232. // directives
  25233. ${shaderData.directives}
  25234. // uniforms
  25235. ${shaderData.uniforms}
  25236. // varyings
  25237. ${shaderData.varyings}
  25238. var<private> varyings : VaryingsStruct;
  25239. // codes
  25240. ${shaderData.codes}
  25241. @vertex
  25242. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  25243. // vars
  25244. ${shaderData.vars}
  25245. // flow
  25246. ${shaderData.flow}
  25247. return varyings;
  25248. }
  25249. `;
  25250. }
  25251. _getWGSLFragmentCode( shaderData ) {
  25252. return `${ this.getSignature() }
  25253. // global
  25254. ${ diagnostics }
  25255. // uniforms
  25256. ${shaderData.uniforms}
  25257. // structs
  25258. ${shaderData.structs}
  25259. // codes
  25260. ${shaderData.codes}
  25261. @fragment
  25262. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  25263. // vars
  25264. ${shaderData.vars}
  25265. // flow
  25266. ${shaderData.flow}
  25267. }
  25268. `;
  25269. }
  25270. _getWGSLComputeCode( shaderData, workgroupSize ) {
  25271. return `${ this.getSignature() }
  25272. // directives
  25273. ${shaderData.directives}
  25274. // system
  25275. var<private> instanceIndex : u32;
  25276. // locals
  25277. ${shaderData.scopedArrays}
  25278. // uniforms
  25279. ${shaderData.uniforms}
  25280. // codes
  25281. ${shaderData.codes}
  25282. @compute @workgroup_size( ${workgroupSize} )
  25283. fn main( ${shaderData.attributes} ) {
  25284. // system
  25285. instanceIndex = id.x + id.y * numWorkgroups.x * u32(${workgroupSize}) + id.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  25286. // vars
  25287. ${shaderData.vars}
  25288. // flow
  25289. ${shaderData.flow}
  25290. }
  25291. `;
  25292. }
  25293. _getWGSLStruct( name, vars ) {
  25294. return `
  25295. struct ${name} {
  25296. ${vars}
  25297. };`;
  25298. }
  25299. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  25300. const structName = name + 'Struct';
  25301. const structSnippet = this._getWGSLStruct( structName, vars );
  25302. return `${structSnippet}
  25303. @binding( ${binding} ) @group( ${group} )
  25304. var<${access}> ${name} : ${structName};`;
  25305. }
  25306. }
  25307. class WebGPUUtils {
  25308. constructor( backend ) {
  25309. this.backend = backend;
  25310. }
  25311. getCurrentDepthStencilFormat( renderContext ) {
  25312. let format;
  25313. if ( renderContext.depthTexture !== null ) {
  25314. format = this.getTextureFormatGPU( renderContext.depthTexture );
  25315. } else if ( renderContext.depth && renderContext.stencil ) {
  25316. format = GPUTextureFormat.Depth24PlusStencil8;
  25317. } else if ( renderContext.depth ) {
  25318. format = GPUTextureFormat.Depth24Plus;
  25319. }
  25320. return format;
  25321. }
  25322. getTextureFormatGPU( texture ) {
  25323. return this.backend.get( texture ).format;
  25324. }
  25325. getCurrentColorFormat( renderContext ) {
  25326. let format;
  25327. if ( renderContext.textures !== null ) {
  25328. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  25329. } else {
  25330. format = this.getPreferredCanvasFormat(); // default context format
  25331. }
  25332. return format;
  25333. }
  25334. getCurrentColorSpace( renderContext ) {
  25335. if ( renderContext.textures !== null ) {
  25336. return renderContext.textures[ 0 ].colorSpace;
  25337. }
  25338. return this.backend.renderer.outputColorSpace;
  25339. }
  25340. getPrimitiveTopology( object, material ) {
  25341. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  25342. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  25343. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  25344. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  25345. }
  25346. getSampleCount( sampleCount ) {
  25347. let count = 1;
  25348. if ( sampleCount > 1 ) {
  25349. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  25350. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  25351. if ( count === 2 ) {
  25352. count = 4;
  25353. }
  25354. }
  25355. return count;
  25356. }
  25357. getSampleCountRenderContext( renderContext ) {
  25358. if ( renderContext.textures !== null ) {
  25359. return this.getSampleCount( renderContext.sampleCount );
  25360. }
  25361. return this.getSampleCount( this.backend.renderer.samples );
  25362. }
  25363. getPreferredCanvasFormat() {
  25364. // TODO: Remove this check when Quest 34.5 is out
  25365. // https://github.com/mrdoob/three.js/pull/29221/files#r1731833949
  25366. if ( navigator.userAgent.includes( 'Quest' ) ) {
  25367. return GPUTextureFormat.BGRA8Unorm;
  25368. } else {
  25369. return navigator.gpu.getPreferredCanvasFormat();
  25370. }
  25371. }
  25372. }
  25373. const typedArraysToVertexFormatPrefix = new Map( [
  25374. [ Int8Array, [ 'sint8', 'snorm8' ]],
  25375. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  25376. [ Int16Array, [ 'sint16', 'snorm16' ]],
  25377. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  25378. [ Int32Array, [ 'sint32', 'snorm32' ]],
  25379. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  25380. [ Float32Array, [ 'float32', ]],
  25381. ] );
  25382. const typedAttributeToVertexFormatPrefix = new Map( [
  25383. [ Float16BufferAttribute, [ 'float16', ]],
  25384. ] );
  25385. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  25386. [ Int32Array, 'sint32' ],
  25387. [ Int16Array, 'sint32' ], // patch for INT16
  25388. [ Uint32Array, 'uint32' ],
  25389. [ Uint16Array, 'uint32' ], // patch for UINT16
  25390. [ Float32Array, 'float32' ]
  25391. ] );
  25392. class WebGPUAttributeUtils {
  25393. constructor( backend ) {
  25394. this.backend = backend;
  25395. }
  25396. createAttribute( attribute, usage ) {
  25397. const bufferAttribute = this._getBufferAttribute( attribute );
  25398. const backend = this.backend;
  25399. const bufferData = backend.get( bufferAttribute );
  25400. let buffer = bufferData.buffer;
  25401. if ( buffer === undefined ) {
  25402. const device = backend.device;
  25403. let array = bufferAttribute.array;
  25404. // patch for INT16 and UINT16
  25405. if ( attribute.normalized === false && ( array.constructor === Int16Array || array.constructor === Uint16Array ) ) {
  25406. const tempArray = new Uint32Array( array.length );
  25407. for ( let i = 0; i < array.length; i ++ ) {
  25408. tempArray[ i ] = array[ i ];
  25409. }
  25410. array = tempArray;
  25411. }
  25412. bufferAttribute.array = array;
  25413. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  25414. array = new array.constructor( bufferAttribute.count * 4 );
  25415. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  25416. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  25417. }
  25418. // Update BufferAttribute
  25419. bufferAttribute.itemSize = 4;
  25420. bufferAttribute.array = array;
  25421. }
  25422. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  25423. buffer = device.createBuffer( {
  25424. label: bufferAttribute.name,
  25425. size: size,
  25426. usage: usage,
  25427. mappedAtCreation: true
  25428. } );
  25429. new array.constructor( buffer.getMappedRange() ).set( array );
  25430. buffer.unmap();
  25431. bufferData.buffer = buffer;
  25432. }
  25433. }
  25434. updateAttribute( attribute ) {
  25435. const bufferAttribute = this._getBufferAttribute( attribute );
  25436. const backend = this.backend;
  25437. const device = backend.device;
  25438. const buffer = backend.get( bufferAttribute ).buffer;
  25439. const array = bufferAttribute.array;
  25440. const isTypedArray = this._isTypedArray( array );
  25441. const updateRanges = bufferAttribute.updateRanges;
  25442. if ( updateRanges.length === 0 ) {
  25443. // Not using update ranges
  25444. device.queue.writeBuffer(
  25445. buffer,
  25446. 0,
  25447. array,
  25448. 0
  25449. );
  25450. } else {
  25451. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  25452. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  25453. const range = updateRanges[ i ];
  25454. const dataOffset = range.start * byteOffsetFactor;
  25455. const size = range.count * byteOffsetFactor;
  25456. device.queue.writeBuffer(
  25457. buffer,
  25458. 0,
  25459. array,
  25460. dataOffset,
  25461. size
  25462. );
  25463. }
  25464. bufferAttribute.clearUpdateRanges();
  25465. }
  25466. }
  25467. createShaderVertexBuffers( renderObject ) {
  25468. const attributes = renderObject.getAttributes();
  25469. const vertexBuffers = new Map();
  25470. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  25471. const geometryAttribute = attributes[ slot ];
  25472. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  25473. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  25474. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  25475. if ( vertexBufferLayout === undefined ) {
  25476. let arrayStride, stepMode;
  25477. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  25478. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  25479. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  25480. } else {
  25481. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  25482. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  25483. }
  25484. // patch for INT16 and UINT16
  25485. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  25486. arrayStride = 4;
  25487. }
  25488. vertexBufferLayout = {
  25489. arrayStride,
  25490. attributes: [],
  25491. stepMode
  25492. };
  25493. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  25494. }
  25495. const format = this._getVertexFormat( geometryAttribute );
  25496. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  25497. vertexBufferLayout.attributes.push( {
  25498. shaderLocation: slot,
  25499. offset,
  25500. format
  25501. } );
  25502. }
  25503. return Array.from( vertexBuffers.values() );
  25504. }
  25505. destroyAttribute( attribute ) {
  25506. const backend = this.backend;
  25507. const data = backend.get( this._getBufferAttribute( attribute ) );
  25508. data.buffer.destroy();
  25509. backend.delete( attribute );
  25510. }
  25511. async getArrayBufferAsync( attribute ) {
  25512. const backend = this.backend;
  25513. const device = backend.device;
  25514. const data = backend.get( this._getBufferAttribute( attribute ) );
  25515. const bufferGPU = data.buffer;
  25516. const size = bufferGPU.size;
  25517. const readBufferGPU = device.createBuffer( {
  25518. label: attribute.name,
  25519. size,
  25520. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  25521. } );
  25522. const cmdEncoder = device.createCommandEncoder( {} );
  25523. cmdEncoder.copyBufferToBuffer(
  25524. bufferGPU,
  25525. 0,
  25526. readBufferGPU,
  25527. 0,
  25528. size
  25529. );
  25530. readBufferGPU.unmap();
  25531. const gpuCommands = cmdEncoder.finish();
  25532. device.queue.submit( [ gpuCommands ] );
  25533. await readBufferGPU.mapAsync( GPUMapMode.READ );
  25534. const arrayBuffer = readBufferGPU.getMappedRange();
  25535. return arrayBuffer;
  25536. }
  25537. _getVertexFormat( geometryAttribute ) {
  25538. const { itemSize, normalized } = geometryAttribute;
  25539. const ArrayType = geometryAttribute.array.constructor;
  25540. const AttributeType = geometryAttribute.constructor;
  25541. let format;
  25542. if ( itemSize == 1 ) {
  25543. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  25544. } else {
  25545. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  25546. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  25547. if ( prefix ) {
  25548. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  25549. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  25550. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  25551. if ( paddedItemSize % 1 ) {
  25552. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  25553. }
  25554. format = `${prefix}x${paddedItemSize}`;
  25555. }
  25556. }
  25557. if ( ! format ) {
  25558. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  25559. }
  25560. return format;
  25561. }
  25562. _isTypedArray( array ) {
  25563. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  25564. }
  25565. _getBufferAttribute( attribute ) {
  25566. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  25567. return attribute;
  25568. }
  25569. }
  25570. class WebGPUBindingUtils {
  25571. constructor( backend ) {
  25572. this.backend = backend;
  25573. this.bindGroupLayoutCache = new WeakMap();
  25574. }
  25575. createBindingsLayout( bindGroup ) {
  25576. const backend = this.backend;
  25577. const device = backend.device;
  25578. const entries = [];
  25579. let index = 0;
  25580. for ( const binding of bindGroup.bindings ) {
  25581. const bindingGPU = {
  25582. binding: index ++,
  25583. visibility: binding.visibility
  25584. };
  25585. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  25586. const buffer = {}; // GPUBufferBindingLayout
  25587. if ( binding.isStorageBuffer ) {
  25588. if ( binding.visibility & 4 ) {
  25589. // compute
  25590. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  25591. buffer.type = GPUBufferBindingType.Storage;
  25592. } else {
  25593. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  25594. }
  25595. } else {
  25596. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  25597. }
  25598. }
  25599. bindingGPU.buffer = buffer;
  25600. } else if ( binding.isSampler ) {
  25601. const sampler = {}; // GPUSamplerBindingLayout
  25602. if ( binding.texture.isDepthTexture ) {
  25603. if ( binding.texture.compareFunction !== null ) {
  25604. sampler.type = 'comparison';
  25605. }
  25606. }
  25607. bindingGPU.sampler = sampler;
  25608. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  25609. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  25610. } else if ( binding.isSampledTexture && binding.store ) {
  25611. const storageTexture = {}; // GPUStorageTextureBindingLayout
  25612. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  25613. const access = binding.access;
  25614. if ( access === NodeAccess.READ_WRITE ) {
  25615. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  25616. } else if ( access === NodeAccess.WRITE_ONLY ) {
  25617. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  25618. } else {
  25619. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  25620. }
  25621. bindingGPU.storageTexture = storageTexture;
  25622. } else if ( binding.isSampledTexture ) {
  25623. const texture = {}; // GPUTextureBindingLayout
  25624. if ( binding.texture.isMultisampleRenderTargetTexture === true ) {
  25625. texture.multisampled = true;
  25626. }
  25627. if ( binding.texture.isDepthTexture ) {
  25628. texture.sampleType = GPUTextureSampleType.Depth;
  25629. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  25630. const type = binding.texture.type;
  25631. if ( type === IntType ) {
  25632. texture.sampleType = GPUTextureSampleType.SInt;
  25633. } else if ( type === UnsignedIntType ) {
  25634. texture.sampleType = GPUTextureSampleType.UInt;
  25635. } else if ( type === FloatType ) {
  25636. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  25637. texture.sampleType = GPUTextureSampleType.Float;
  25638. } else {
  25639. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  25640. }
  25641. }
  25642. }
  25643. if ( binding.isSampledCubeTexture ) {
  25644. texture.viewDimension = GPUTextureViewDimension.Cube;
  25645. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  25646. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  25647. } else if ( binding.isSampledTexture3D ) {
  25648. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  25649. }
  25650. bindingGPU.texture = texture;
  25651. } else {
  25652. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  25653. }
  25654. entries.push( bindingGPU );
  25655. }
  25656. return device.createBindGroupLayout( { entries } );
  25657. }
  25658. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  25659. const { backend, bindGroupLayoutCache } = this;
  25660. const bindingsData = backend.get( bindGroup );
  25661. // setup (static) binding layout and (dynamic) binding group
  25662. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  25663. if ( bindLayoutGPU === undefined ) {
  25664. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  25665. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  25666. }
  25667. let bindGroupGPU;
  25668. if ( cacheIndex > 0 ) {
  25669. if ( bindingsData.groups === undefined ) {
  25670. bindingsData.groups = [];
  25671. bindingsData.versions = [];
  25672. }
  25673. if ( bindingsData.versions[ cacheIndex ] === version ) {
  25674. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  25675. }
  25676. }
  25677. if ( bindGroupGPU === undefined ) {
  25678. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  25679. if ( cacheIndex > 0 ) {
  25680. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  25681. bindingsData.versions[ cacheIndex ] = version;
  25682. }
  25683. }
  25684. bindingsData.group = bindGroupGPU;
  25685. bindingsData.layout = bindLayoutGPU;
  25686. }
  25687. updateBinding( binding ) {
  25688. const backend = this.backend;
  25689. const device = backend.device;
  25690. const buffer = binding.buffer;
  25691. const bufferGPU = backend.get( binding ).buffer;
  25692. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  25693. }
  25694. createBindGroup( bindGroup, layoutGPU ) {
  25695. const backend = this.backend;
  25696. const device = backend.device;
  25697. let bindingPoint = 0;
  25698. const entriesGPU = [];
  25699. for ( const binding of bindGroup.bindings ) {
  25700. if ( binding.isUniformBuffer ) {
  25701. const bindingData = backend.get( binding );
  25702. if ( bindingData.buffer === undefined ) {
  25703. const byteLength = binding.byteLength;
  25704. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  25705. const bufferGPU = device.createBuffer( {
  25706. label: 'bindingBuffer_' + binding.name,
  25707. size: byteLength,
  25708. usage: usage
  25709. } );
  25710. bindingData.buffer = bufferGPU;
  25711. }
  25712. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  25713. } else if ( binding.isStorageBuffer ) {
  25714. const bindingData = backend.get( binding );
  25715. if ( bindingData.buffer === undefined ) {
  25716. const attribute = binding.attribute;
  25717. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  25718. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  25719. bindingData.buffer = backend.get( attribute ).buffer;
  25720. }
  25721. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  25722. } else if ( binding.isSampler ) {
  25723. const textureGPU = backend.get( binding.texture );
  25724. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  25725. } else if ( binding.isSampledTexture ) {
  25726. const textureData = backend.get( binding.texture );
  25727. let resourceGPU;
  25728. if ( textureData.externalTexture !== undefined ) {
  25729. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  25730. } else {
  25731. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  25732. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  25733. resourceGPU = textureData[ propertyName ];
  25734. if ( resourceGPU === undefined ) {
  25735. const aspectGPU = GPUTextureAspect.All;
  25736. let dimensionViewGPU;
  25737. if ( binding.isSampledCubeTexture ) {
  25738. dimensionViewGPU = GPUTextureViewDimension.Cube;
  25739. } else if ( binding.isSampledTexture3D ) {
  25740. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  25741. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  25742. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  25743. } else {
  25744. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  25745. }
  25746. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  25747. }
  25748. }
  25749. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  25750. }
  25751. bindingPoint ++;
  25752. }
  25753. return device.createBindGroup( {
  25754. label: 'bindGroup_' + bindGroup.name,
  25755. layout: layoutGPU,
  25756. entries: entriesGPU
  25757. } );
  25758. }
  25759. }
  25760. class WebGPUPipelineUtils {
  25761. constructor( backend ) {
  25762. this.backend = backend;
  25763. }
  25764. _getSampleCount( renderObjectContext ) {
  25765. return this.backend.utils.getSampleCountRenderContext( renderObjectContext );
  25766. }
  25767. createRenderPipeline( renderObject, promises ) {
  25768. const { object, material, geometry, pipeline } = renderObject;
  25769. const { vertexProgram, fragmentProgram } = pipeline;
  25770. const backend = this.backend;
  25771. const device = backend.device;
  25772. const utils = backend.utils;
  25773. const pipelineData = backend.get( pipeline );
  25774. // bind group layouts
  25775. const bindGroupLayouts = [];
  25776. for ( const bindGroup of renderObject.getBindings() ) {
  25777. const bindingsData = backend.get( bindGroup );
  25778. bindGroupLayouts.push( bindingsData.layout );
  25779. }
  25780. // vertex buffers
  25781. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  25782. // blending
  25783. let blending;
  25784. if ( material.transparent === true && material.blending !== NoBlending ) {
  25785. blending = this._getBlending( material );
  25786. }
  25787. // stencil
  25788. let stencilFront = {};
  25789. if ( material.stencilWrite === true ) {
  25790. stencilFront = {
  25791. compare: this._getStencilCompare( material ),
  25792. failOp: this._getStencilOperation( material.stencilFail ),
  25793. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  25794. passOp: this._getStencilOperation( material.stencilZPass )
  25795. };
  25796. }
  25797. const colorWriteMask = this._getColorWriteMask( material );
  25798. const targets = [];
  25799. if ( renderObject.context.textures !== null ) {
  25800. const textures = renderObject.context.textures;
  25801. for ( let i = 0; i < textures.length; i ++ ) {
  25802. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  25803. targets.push( {
  25804. format: colorFormat,
  25805. blend: blending,
  25806. writeMask: colorWriteMask
  25807. } );
  25808. }
  25809. } else {
  25810. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  25811. targets.push( {
  25812. format: colorFormat,
  25813. blend: blending,
  25814. writeMask: colorWriteMask
  25815. } );
  25816. }
  25817. const vertexModule = backend.get( vertexProgram ).module;
  25818. const fragmentModule = backend.get( fragmentProgram ).module;
  25819. const primitiveState = this._getPrimitiveState( object, geometry, material );
  25820. const depthCompare = this._getDepthCompare( material );
  25821. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  25822. const sampleCount = this._getSampleCount( renderObject.context );
  25823. const pipelineDescriptor = {
  25824. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  25825. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  25826. fragment: Object.assign( {}, fragmentModule, { targets } ),
  25827. primitive: primitiveState,
  25828. multisample: {
  25829. count: sampleCount,
  25830. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  25831. },
  25832. layout: device.createPipelineLayout( {
  25833. bindGroupLayouts
  25834. } )
  25835. };
  25836. const depthStencil = {};
  25837. const renderDepth = renderObject.context.depth;
  25838. const renderStencil = renderObject.context.stencil;
  25839. if ( renderDepth === true || renderStencil === true ) {
  25840. if ( renderDepth === true ) {
  25841. depthStencil.format = depthStencilFormat;
  25842. depthStencil.depthWriteEnabled = material.depthWrite;
  25843. depthStencil.depthCompare = depthCompare;
  25844. }
  25845. if ( renderStencil === true ) {
  25846. depthStencil.stencilFront = stencilFront;
  25847. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  25848. depthStencil.stencilReadMask = material.stencilFuncMask;
  25849. depthStencil.stencilWriteMask = material.stencilWriteMask;
  25850. }
  25851. pipelineDescriptor.depthStencil = depthStencil;
  25852. }
  25853. if ( promises === null ) {
  25854. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  25855. } else {
  25856. const p = new Promise( ( resolve /*, reject*/ ) => {
  25857. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  25858. pipelineData.pipeline = pipeline;
  25859. resolve();
  25860. } );
  25861. } );
  25862. promises.push( p );
  25863. }
  25864. }
  25865. createBundleEncoder( renderContext ) {
  25866. const backend = this.backend;
  25867. const { utils, device } = backend;
  25868. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  25869. const colorFormat = utils.getCurrentColorFormat( renderContext );
  25870. const sampleCount = this._getSampleCount( renderContext );
  25871. const descriptor = {
  25872. label: 'renderBundleEncoder',
  25873. colorFormats: [ colorFormat ],
  25874. depthStencilFormat,
  25875. sampleCount
  25876. };
  25877. return device.createRenderBundleEncoder( descriptor );
  25878. }
  25879. createComputePipeline( pipeline, bindings ) {
  25880. const backend = this.backend;
  25881. const device = backend.device;
  25882. const computeProgram = backend.get( pipeline.computeProgram ).module;
  25883. const pipelineGPU = backend.get( pipeline );
  25884. // bind group layouts
  25885. const bindGroupLayouts = [];
  25886. for ( const bindingsGroup of bindings ) {
  25887. const bindingsData = backend.get( bindingsGroup );
  25888. bindGroupLayouts.push( bindingsData.layout );
  25889. }
  25890. pipelineGPU.pipeline = device.createComputePipeline( {
  25891. compute: computeProgram,
  25892. layout: device.createPipelineLayout( {
  25893. bindGroupLayouts
  25894. } )
  25895. } );
  25896. }
  25897. _getBlending( material ) {
  25898. let color, alpha;
  25899. const blending = material.blending;
  25900. const blendSrc = material.blendSrc;
  25901. const blendDst = material.blendDst;
  25902. const blendEquation = material.blendEquation;
  25903. if ( blending === CustomBlending ) {
  25904. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  25905. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  25906. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  25907. color = {
  25908. srcFactor: this._getBlendFactor( blendSrc ),
  25909. dstFactor: this._getBlendFactor( blendDst ),
  25910. operation: this._getBlendOperation( blendEquation )
  25911. };
  25912. alpha = {
  25913. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  25914. dstFactor: this._getBlendFactor( blendDstAlpha ),
  25915. operation: this._getBlendOperation( blendEquationAlpha )
  25916. };
  25917. } else {
  25918. const premultipliedAlpha = material.premultipliedAlpha;
  25919. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  25920. color = {
  25921. srcFactor: srcRGB,
  25922. dstFactor: dstRGB,
  25923. operation: GPUBlendOperation.Add
  25924. };
  25925. alpha = {
  25926. srcFactor: srcAlpha,
  25927. dstFactor: dstAlpha,
  25928. operation: GPUBlendOperation.Add
  25929. };
  25930. };
  25931. if ( premultipliedAlpha ) {
  25932. switch ( blending ) {
  25933. case NormalBlending:
  25934. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  25935. break;
  25936. case AdditiveBlending:
  25937. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  25938. break;
  25939. case SubtractiveBlending:
  25940. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  25941. break;
  25942. case MultiplyBlending:
  25943. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  25944. break;
  25945. }
  25946. } else {
  25947. switch ( blending ) {
  25948. case NormalBlending:
  25949. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  25950. break;
  25951. case AdditiveBlending:
  25952. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  25953. break;
  25954. case SubtractiveBlending:
  25955. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  25956. break;
  25957. case MultiplyBlending:
  25958. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  25959. break;
  25960. }
  25961. }
  25962. }
  25963. if ( color !== undefined && alpha !== undefined ) {
  25964. return { color, alpha };
  25965. } else {
  25966. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  25967. }
  25968. }
  25969. _getBlendFactor( blend ) {
  25970. let blendFactor;
  25971. switch ( blend ) {
  25972. case ZeroFactor:
  25973. blendFactor = GPUBlendFactor.Zero;
  25974. break;
  25975. case OneFactor:
  25976. blendFactor = GPUBlendFactor.One;
  25977. break;
  25978. case SrcColorFactor:
  25979. blendFactor = GPUBlendFactor.Src;
  25980. break;
  25981. case OneMinusSrcColorFactor:
  25982. blendFactor = GPUBlendFactor.OneMinusSrc;
  25983. break;
  25984. case SrcAlphaFactor:
  25985. blendFactor = GPUBlendFactor.SrcAlpha;
  25986. break;
  25987. case OneMinusSrcAlphaFactor:
  25988. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  25989. break;
  25990. case DstColorFactor:
  25991. blendFactor = GPUBlendFactor.Dst;
  25992. break;
  25993. case OneMinusDstColorFactor:
  25994. blendFactor = GPUBlendFactor.OneMinusDstColor;
  25995. break;
  25996. case DstAlphaFactor:
  25997. blendFactor = GPUBlendFactor.DstAlpha;
  25998. break;
  25999. case OneMinusDstAlphaFactor:
  26000. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  26001. break;
  26002. case SrcAlphaSaturateFactor:
  26003. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  26004. break;
  26005. case BlendColorFactor:
  26006. blendFactor = GPUBlendFactor.Constant;
  26007. break;
  26008. case OneMinusBlendColorFactor:
  26009. blendFactor = GPUBlendFactor.OneMinusConstant;
  26010. break;
  26011. default:
  26012. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  26013. }
  26014. return blendFactor;
  26015. }
  26016. _getStencilCompare( material ) {
  26017. let stencilCompare;
  26018. const stencilFunc = material.stencilFunc;
  26019. switch ( stencilFunc ) {
  26020. case NeverStencilFunc:
  26021. stencilCompare = GPUCompareFunction.Never;
  26022. break;
  26023. case AlwaysStencilFunc:
  26024. stencilCompare = GPUCompareFunction.Always;
  26025. break;
  26026. case LessStencilFunc:
  26027. stencilCompare = GPUCompareFunction.Less;
  26028. break;
  26029. case LessEqualStencilFunc:
  26030. stencilCompare = GPUCompareFunction.LessEqual;
  26031. break;
  26032. case EqualStencilFunc:
  26033. stencilCompare = GPUCompareFunction.Equal;
  26034. break;
  26035. case GreaterEqualStencilFunc:
  26036. stencilCompare = GPUCompareFunction.GreaterEqual;
  26037. break;
  26038. case GreaterStencilFunc:
  26039. stencilCompare = GPUCompareFunction.Greater;
  26040. break;
  26041. case NotEqualStencilFunc:
  26042. stencilCompare = GPUCompareFunction.NotEqual;
  26043. break;
  26044. default:
  26045. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  26046. }
  26047. return stencilCompare;
  26048. }
  26049. _getStencilOperation( op ) {
  26050. let stencilOperation;
  26051. switch ( op ) {
  26052. case KeepStencilOp:
  26053. stencilOperation = GPUStencilOperation.Keep;
  26054. break;
  26055. case ZeroStencilOp:
  26056. stencilOperation = GPUStencilOperation.Zero;
  26057. break;
  26058. case ReplaceStencilOp:
  26059. stencilOperation = GPUStencilOperation.Replace;
  26060. break;
  26061. case InvertStencilOp:
  26062. stencilOperation = GPUStencilOperation.Invert;
  26063. break;
  26064. case IncrementStencilOp:
  26065. stencilOperation = GPUStencilOperation.IncrementClamp;
  26066. break;
  26067. case DecrementStencilOp:
  26068. stencilOperation = GPUStencilOperation.DecrementClamp;
  26069. break;
  26070. case IncrementWrapStencilOp:
  26071. stencilOperation = GPUStencilOperation.IncrementWrap;
  26072. break;
  26073. case DecrementWrapStencilOp:
  26074. stencilOperation = GPUStencilOperation.DecrementWrap;
  26075. break;
  26076. default:
  26077. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  26078. }
  26079. return stencilOperation;
  26080. }
  26081. _getBlendOperation( blendEquation ) {
  26082. let blendOperation;
  26083. switch ( blendEquation ) {
  26084. case AddEquation:
  26085. blendOperation = GPUBlendOperation.Add;
  26086. break;
  26087. case SubtractEquation:
  26088. blendOperation = GPUBlendOperation.Subtract;
  26089. break;
  26090. case ReverseSubtractEquation:
  26091. blendOperation = GPUBlendOperation.ReverseSubtract;
  26092. break;
  26093. case MinEquation:
  26094. blendOperation = GPUBlendOperation.Min;
  26095. break;
  26096. case MaxEquation:
  26097. blendOperation = GPUBlendOperation.Max;
  26098. break;
  26099. default:
  26100. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  26101. }
  26102. return blendOperation;
  26103. }
  26104. _getPrimitiveState( object, geometry, material ) {
  26105. const descriptor = {};
  26106. const utils = this.backend.utils;
  26107. descriptor.topology = utils.getPrimitiveTopology( object, material );
  26108. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  26109. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  26110. }
  26111. switch ( material.side ) {
  26112. case FrontSide:
  26113. descriptor.frontFace = GPUFrontFace.CCW;
  26114. descriptor.cullMode = GPUCullMode.Back;
  26115. break;
  26116. case BackSide:
  26117. descriptor.frontFace = GPUFrontFace.CCW;
  26118. descriptor.cullMode = GPUCullMode.Front;
  26119. break;
  26120. case DoubleSide:
  26121. descriptor.frontFace = GPUFrontFace.CCW;
  26122. descriptor.cullMode = GPUCullMode.None;
  26123. break;
  26124. default:
  26125. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  26126. break;
  26127. }
  26128. return descriptor;
  26129. }
  26130. _getColorWriteMask( material ) {
  26131. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  26132. }
  26133. _getDepthCompare( material ) {
  26134. let depthCompare;
  26135. if ( material.depthTest === false ) {
  26136. depthCompare = GPUCompareFunction.Always;
  26137. } else {
  26138. const depthFunc = material.depthFunc;
  26139. switch ( depthFunc ) {
  26140. case NeverDepth:
  26141. depthCompare = GPUCompareFunction.Never;
  26142. break;
  26143. case AlwaysDepth:
  26144. depthCompare = GPUCompareFunction.Always;
  26145. break;
  26146. case LessDepth:
  26147. depthCompare = GPUCompareFunction.Less;
  26148. break;
  26149. case LessEqualDepth:
  26150. depthCompare = GPUCompareFunction.LessEqual;
  26151. break;
  26152. case EqualDepth:
  26153. depthCompare = GPUCompareFunction.Equal;
  26154. break;
  26155. case GreaterEqualDepth:
  26156. depthCompare = GPUCompareFunction.GreaterEqual;
  26157. break;
  26158. case GreaterDepth:
  26159. depthCompare = GPUCompareFunction.Greater;
  26160. break;
  26161. case NotEqualDepth:
  26162. depthCompare = GPUCompareFunction.NotEqual;
  26163. break;
  26164. default:
  26165. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  26166. }
  26167. }
  26168. return depthCompare;
  26169. }
  26170. }
  26171. /*// debugger tools
  26172. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  26173. //*/
  26174. //
  26175. class WebGPUBackend extends Backend {
  26176. constructor( parameters = {} ) {
  26177. super( parameters );
  26178. this.isWebGPUBackend = true;
  26179. // some parameters require default values other than "undefined"
  26180. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  26181. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  26182. this.trackTimestamp = ( parameters.trackTimestamp === true );
  26183. this.device = null;
  26184. this.context = null;
  26185. this.colorBuffer = null;
  26186. this.defaultRenderPassdescriptor = null;
  26187. this.utils = new WebGPUUtils( this );
  26188. this.attributeUtils = new WebGPUAttributeUtils( this );
  26189. this.bindingUtils = new WebGPUBindingUtils( this );
  26190. this.pipelineUtils = new WebGPUPipelineUtils( this );
  26191. this.textureUtils = new WebGPUTextureUtils( this );
  26192. this.occludedResolveCache = new Map();
  26193. }
  26194. async init( renderer ) {
  26195. await super.init( renderer );
  26196. //
  26197. const parameters = this.parameters;
  26198. // create the device if it is not passed with parameters
  26199. let device;
  26200. if ( parameters.device === undefined ) {
  26201. const adapterOptions = {
  26202. powerPreference: parameters.powerPreference
  26203. };
  26204. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  26205. if ( adapter === null ) {
  26206. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  26207. }
  26208. // feature support
  26209. const features = Object.values( GPUFeatureName );
  26210. const supportedFeatures = [];
  26211. for ( const name of features ) {
  26212. if ( adapter.features.has( name ) ) {
  26213. supportedFeatures.push( name );
  26214. }
  26215. }
  26216. const deviceDescriptor = {
  26217. requiredFeatures: supportedFeatures,
  26218. requiredLimits: parameters.requiredLimits
  26219. };
  26220. device = await adapter.requestDevice( deviceDescriptor );
  26221. } else {
  26222. device = parameters.device;
  26223. }
  26224. device.lost.then( ( info ) => {
  26225. const deviceLossInfo = {
  26226. api: 'WebGPU',
  26227. message: info.message || 'Unknown reason',
  26228. reason: info.reason || null,
  26229. originalEvent: info
  26230. };
  26231. renderer.onDeviceLost( deviceLossInfo );
  26232. } );
  26233. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  26234. this.device = device;
  26235. this.context = context;
  26236. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  26237. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  26238. this.context.configure( {
  26239. device: this.device,
  26240. format: this.utils.getPreferredCanvasFormat(),
  26241. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  26242. alphaMode: alphaMode
  26243. } );
  26244. this.updateSize();
  26245. }
  26246. get coordinateSystem() {
  26247. return WebGPUCoordinateSystem;
  26248. }
  26249. async getArrayBufferAsync( attribute ) {
  26250. return await this.attributeUtils.getArrayBufferAsync( attribute );
  26251. }
  26252. getContext() {
  26253. return this.context;
  26254. }
  26255. _getDefaultRenderPassDescriptor() {
  26256. let descriptor = this.defaultRenderPassdescriptor;
  26257. if ( descriptor === null ) {
  26258. const renderer = this.renderer;
  26259. descriptor = {
  26260. colorAttachments: [ {
  26261. view: null
  26262. } ],
  26263. };
  26264. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  26265. descriptor.depthStencilAttachment = {
  26266. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  26267. };
  26268. }
  26269. const colorAttachment = descriptor.colorAttachments[ 0 ];
  26270. if ( this.renderer.samples > 0 ) {
  26271. colorAttachment.view = this.colorBuffer.createView();
  26272. } else {
  26273. colorAttachment.resolveTarget = undefined;
  26274. }
  26275. this.defaultRenderPassdescriptor = descriptor;
  26276. }
  26277. const colorAttachment = descriptor.colorAttachments[ 0 ];
  26278. if ( this.renderer.samples > 0 ) {
  26279. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  26280. } else {
  26281. colorAttachment.view = this.context.getCurrentTexture().createView();
  26282. }
  26283. return descriptor;
  26284. }
  26285. _getRenderPassDescriptor( renderContext ) {
  26286. const renderTarget = renderContext.renderTarget;
  26287. const renderTargetData = this.get( renderTarget );
  26288. let descriptors = renderTargetData.descriptors;
  26289. if ( descriptors === undefined ||
  26290. renderTargetData.width !== renderTarget.width ||
  26291. renderTargetData.height !== renderTarget.height ||
  26292. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  26293. renderTargetData.samples !== renderTarget.samples
  26294. ) {
  26295. descriptors = {};
  26296. renderTargetData.descriptors = descriptors;
  26297. // dispose
  26298. const onDispose = () => {
  26299. renderTarget.removeEventListener( 'dispose', onDispose );
  26300. this.delete( renderTarget );
  26301. };
  26302. renderTarget.addEventListener( 'dispose', onDispose );
  26303. }
  26304. const cacheKey = renderContext.getCacheKey();
  26305. let descriptor = descriptors[ cacheKey ];
  26306. if ( descriptor === undefined ) {
  26307. const textures = renderContext.textures;
  26308. const colorAttachments = [];
  26309. for ( let i = 0; i < textures.length; i ++ ) {
  26310. const textureData = this.get( textures[ i ] );
  26311. const textureView = textureData.texture.createView( {
  26312. baseMipLevel: renderContext.activeMipmapLevel,
  26313. mipLevelCount: 1,
  26314. baseArrayLayer: renderContext.activeCubeFace,
  26315. dimension: GPUTextureViewDimension.TwoD
  26316. } );
  26317. let view, resolveTarget;
  26318. if ( textureData.msaaTexture !== undefined ) {
  26319. view = textureData.msaaTexture.createView();
  26320. resolveTarget = textureView;
  26321. } else {
  26322. view = textureView;
  26323. resolveTarget = undefined;
  26324. }
  26325. colorAttachments.push( {
  26326. view,
  26327. resolveTarget,
  26328. loadOp: GPULoadOp.Load,
  26329. storeOp: GPUStoreOp.Store
  26330. } );
  26331. }
  26332. descriptor = {
  26333. colorAttachments,
  26334. };
  26335. if ( renderContext.depth ) {
  26336. const depthTextureData = this.get( renderContext.depthTexture );
  26337. const depthStencilAttachment = {
  26338. view: depthTextureData.texture.createView()
  26339. };
  26340. descriptor.depthStencilAttachment = depthStencilAttachment;
  26341. }
  26342. descriptors[ cacheKey ] = descriptor;
  26343. renderTargetData.width = renderTarget.width;
  26344. renderTargetData.height = renderTarget.height;
  26345. renderTargetData.samples = renderTarget.samples;
  26346. renderTargetData.activeMipmapLevel = renderTarget.activeMipmapLevel;
  26347. }
  26348. return descriptor;
  26349. }
  26350. beginRender( renderContext ) {
  26351. const renderContextData = this.get( renderContext );
  26352. const device = this.device;
  26353. const occlusionQueryCount = renderContext.occlusionQueryCount;
  26354. let occlusionQuerySet;
  26355. if ( occlusionQueryCount > 0 ) {
  26356. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  26357. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  26358. // Get a reference to the array of objects with queries. The renderContextData property
  26359. // can be changed by another render pass before the buffer.mapAsyc() completes.
  26360. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  26361. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  26362. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  26363. //
  26364. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  26365. renderContextData.occlusionQuerySet = occlusionQuerySet;
  26366. renderContextData.occlusionQueryIndex = 0;
  26367. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  26368. renderContextData.lastOcclusionObject = null;
  26369. }
  26370. let descriptor;
  26371. if ( renderContext.textures === null ) {
  26372. descriptor = this._getDefaultRenderPassDescriptor();
  26373. } else {
  26374. descriptor = this._getRenderPassDescriptor( renderContext );
  26375. }
  26376. this.initTimestampQuery( renderContext, descriptor );
  26377. descriptor.occlusionQuerySet = occlusionQuerySet;
  26378. const depthStencilAttachment = descriptor.depthStencilAttachment;
  26379. if ( renderContext.textures !== null ) {
  26380. const colorAttachments = descriptor.colorAttachments;
  26381. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  26382. const colorAttachment = colorAttachments[ i ];
  26383. if ( renderContext.clearColor ) {
  26384. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  26385. colorAttachment.loadOp = GPULoadOp.Clear;
  26386. colorAttachment.storeOp = GPUStoreOp.Store;
  26387. } else {
  26388. colorAttachment.loadOp = GPULoadOp.Load;
  26389. colorAttachment.storeOp = GPUStoreOp.Store;
  26390. }
  26391. }
  26392. } else {
  26393. const colorAttachment = descriptor.colorAttachments[ 0 ];
  26394. if ( renderContext.clearColor ) {
  26395. colorAttachment.clearValue = renderContext.clearColorValue;
  26396. colorAttachment.loadOp = GPULoadOp.Clear;
  26397. colorAttachment.storeOp = GPUStoreOp.Store;
  26398. } else {
  26399. colorAttachment.loadOp = GPULoadOp.Load;
  26400. colorAttachment.storeOp = GPUStoreOp.Store;
  26401. }
  26402. }
  26403. //
  26404. if ( renderContext.depth ) {
  26405. if ( renderContext.clearDepth ) {
  26406. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  26407. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  26408. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  26409. } else {
  26410. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  26411. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  26412. }
  26413. }
  26414. if ( renderContext.stencil ) {
  26415. if ( renderContext.clearStencil ) {
  26416. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  26417. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  26418. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  26419. } else {
  26420. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  26421. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  26422. }
  26423. }
  26424. //
  26425. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  26426. const currentPass = encoder.beginRenderPass( descriptor );
  26427. //
  26428. renderContextData.descriptor = descriptor;
  26429. renderContextData.encoder = encoder;
  26430. renderContextData.currentPass = currentPass;
  26431. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  26432. renderContextData.renderBundles = [];
  26433. //
  26434. if ( renderContext.viewport ) {
  26435. this.updateViewport( renderContext );
  26436. }
  26437. if ( renderContext.scissor ) {
  26438. const { x, y, width, height } = renderContext.scissorValue;
  26439. currentPass.setScissorRect( x, y, width, height );
  26440. }
  26441. }
  26442. finishRender( renderContext ) {
  26443. const renderContextData = this.get( renderContext );
  26444. const occlusionQueryCount = renderContext.occlusionQueryCount;
  26445. if ( renderContextData.renderBundles.length > 0 ) {
  26446. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  26447. }
  26448. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  26449. renderContextData.currentPass.endOcclusionQuery();
  26450. }
  26451. renderContextData.currentPass.end();
  26452. if ( occlusionQueryCount > 0 ) {
  26453. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  26454. //
  26455. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  26456. if ( queryResolveBuffer === undefined ) {
  26457. queryResolveBuffer = this.device.createBuffer(
  26458. {
  26459. size: bufferSize,
  26460. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  26461. }
  26462. );
  26463. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  26464. }
  26465. //
  26466. const readBuffer = this.device.createBuffer(
  26467. {
  26468. size: bufferSize,
  26469. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  26470. }
  26471. );
  26472. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  26473. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  26474. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  26475. renderContextData.occlusionQueryBuffer = readBuffer;
  26476. //
  26477. this.resolveOccludedAsync( renderContext );
  26478. }
  26479. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  26480. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  26481. //
  26482. if ( renderContext.textures !== null ) {
  26483. const textures = renderContext.textures;
  26484. for ( let i = 0; i < textures.length; i ++ ) {
  26485. const texture = textures[ i ];
  26486. if ( texture.generateMipmaps === true ) {
  26487. this.textureUtils.generateMipmaps( texture );
  26488. }
  26489. }
  26490. }
  26491. }
  26492. isOccluded( renderContext, object ) {
  26493. const renderContextData = this.get( renderContext );
  26494. return renderContextData.occluded && renderContextData.occluded.has( object );
  26495. }
  26496. async resolveOccludedAsync( renderContext ) {
  26497. const renderContextData = this.get( renderContext );
  26498. // handle occlusion query results
  26499. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  26500. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  26501. const occluded = new WeakSet();
  26502. renderContextData.currentOcclusionQueryObjects = null;
  26503. renderContextData.currentOcclusionQueryBuffer = null;
  26504. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  26505. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  26506. const results = new BigUint64Array( buffer );
  26507. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  26508. if ( results[ i ] !== BigInt( 0 ) ) {
  26509. occluded.add( currentOcclusionQueryObjects[ i ] );
  26510. }
  26511. }
  26512. currentOcclusionQueryBuffer.destroy();
  26513. renderContextData.occluded = occluded;
  26514. }
  26515. }
  26516. updateViewport( renderContext ) {
  26517. const { currentPass } = this.get( renderContext );
  26518. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  26519. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  26520. }
  26521. clear( color, depth, stencil, renderTargetData = null ) {
  26522. const device = this.device;
  26523. const renderer = this.renderer;
  26524. let colorAttachments = [];
  26525. let depthStencilAttachment;
  26526. let clearValue;
  26527. let supportsDepth;
  26528. let supportsStencil;
  26529. if ( color ) {
  26530. const clearColor = this.getClearColor();
  26531. if ( this.renderer.alpha === true ) {
  26532. // premultiply alpha
  26533. const a = clearColor.a;
  26534. clearValue = { r: clearColor.r * a, g: clearColor.g * a, b: clearColor.b * a, a: a };
  26535. } else {
  26536. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  26537. }
  26538. }
  26539. if ( renderTargetData === null ) {
  26540. supportsDepth = renderer.depth;
  26541. supportsStencil = renderer.stencil;
  26542. const descriptor = this._getDefaultRenderPassDescriptor();
  26543. if ( color ) {
  26544. colorAttachments = descriptor.colorAttachments;
  26545. const colorAttachment = colorAttachments[ 0 ];
  26546. colorAttachment.clearValue = clearValue;
  26547. colorAttachment.loadOp = GPULoadOp.Clear;
  26548. colorAttachment.storeOp = GPUStoreOp.Store;
  26549. }
  26550. if ( supportsDepth || supportsStencil ) {
  26551. depthStencilAttachment = descriptor.depthStencilAttachment;
  26552. }
  26553. } else {
  26554. supportsDepth = renderTargetData.depth;
  26555. supportsStencil = renderTargetData.stencil;
  26556. if ( color ) {
  26557. for ( const texture of renderTargetData.textures ) {
  26558. const textureData = this.get( texture );
  26559. const textureView = textureData.texture.createView();
  26560. let view, resolveTarget;
  26561. if ( textureData.msaaTexture !== undefined ) {
  26562. view = textureData.msaaTexture.createView();
  26563. resolveTarget = textureView;
  26564. } else {
  26565. view = textureView;
  26566. resolveTarget = undefined;
  26567. }
  26568. colorAttachments.push( {
  26569. view,
  26570. resolveTarget,
  26571. clearValue,
  26572. loadOp: GPULoadOp.Clear,
  26573. storeOp: GPUStoreOp.Store
  26574. } );
  26575. }
  26576. }
  26577. if ( supportsDepth || supportsStencil ) {
  26578. const depthTextureData = this.get( renderTargetData.depthTexture );
  26579. depthStencilAttachment = {
  26580. view: depthTextureData.texture.createView()
  26581. };
  26582. }
  26583. }
  26584. //
  26585. if ( supportsDepth ) {
  26586. if ( depth ) {
  26587. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  26588. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  26589. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  26590. } else {
  26591. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  26592. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  26593. }
  26594. }
  26595. //
  26596. if ( supportsStencil ) {
  26597. if ( stencil ) {
  26598. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  26599. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  26600. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  26601. } else {
  26602. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  26603. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  26604. }
  26605. }
  26606. //
  26607. const encoder = device.createCommandEncoder( {} );
  26608. const currentPass = encoder.beginRenderPass( {
  26609. colorAttachments,
  26610. depthStencilAttachment
  26611. } );
  26612. currentPass.end();
  26613. device.queue.submit( [ encoder.finish() ] );
  26614. }
  26615. // compute
  26616. beginCompute( computeGroup ) {
  26617. const groupGPU = this.get( computeGroup );
  26618. const descriptor = {};
  26619. this.initTimestampQuery( computeGroup, descriptor );
  26620. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  26621. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  26622. }
  26623. compute( computeGroup, computeNode, bindings, pipeline ) {
  26624. const { passEncoderGPU } = this.get( computeGroup );
  26625. // pipeline
  26626. const pipelineGPU = this.get( pipeline ).pipeline;
  26627. passEncoderGPU.setPipeline( pipelineGPU );
  26628. // bind groups
  26629. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  26630. const bindGroup = bindings[ i ];
  26631. const bindingsData = this.get( bindGroup );
  26632. passEncoderGPU.setBindGroup( i, bindingsData.group );
  26633. }
  26634. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  26635. const computeNodeData = this.get( computeNode );
  26636. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  26637. const { dispatchSize } = computeNodeData;
  26638. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  26639. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  26640. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  26641. } else {
  26642. dispatchSize.x = computeNode.dispatchCount;
  26643. }
  26644. passEncoderGPU.dispatchWorkgroups(
  26645. dispatchSize.x,
  26646. dispatchSize.y,
  26647. dispatchSize.z
  26648. );
  26649. }
  26650. finishCompute( computeGroup ) {
  26651. const groupData = this.get( computeGroup );
  26652. groupData.passEncoderGPU.end();
  26653. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  26654. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  26655. }
  26656. async waitForGPU() {
  26657. await this.device.queue.onSubmittedWorkDone();
  26658. }
  26659. // render object
  26660. draw( renderObject, info ) {
  26661. const { object, context, pipeline } = renderObject;
  26662. const bindings = renderObject.getBindings();
  26663. const renderContextData = this.get( context );
  26664. const pipelineGPU = this.get( pipeline ).pipeline;
  26665. const currentSets = renderContextData.currentSets;
  26666. const passEncoderGPU = renderContextData.currentPass;
  26667. const drawParams = renderObject.getDrawParameters();
  26668. if ( drawParams === null ) return;
  26669. // pipeline
  26670. if ( currentSets.pipeline !== pipelineGPU ) {
  26671. passEncoderGPU.setPipeline( pipelineGPU );
  26672. currentSets.pipeline = pipelineGPU;
  26673. }
  26674. // bind groups
  26675. const currentBindingGroups = currentSets.bindingGroups;
  26676. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  26677. const bindGroup = bindings[ i ];
  26678. const bindingsData = this.get( bindGroup );
  26679. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  26680. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  26681. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  26682. }
  26683. }
  26684. // attributes
  26685. const index = renderObject.getIndex();
  26686. const hasIndex = ( index !== null );
  26687. // index
  26688. if ( hasIndex === true ) {
  26689. if ( currentSets.index !== index ) {
  26690. const buffer = this.get( index ).buffer;
  26691. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  26692. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  26693. currentSets.index = index;
  26694. }
  26695. }
  26696. // vertex buffers
  26697. const vertexBuffers = renderObject.getVertexBuffers();
  26698. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  26699. const vertexBuffer = vertexBuffers[ i ];
  26700. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  26701. const buffer = this.get( vertexBuffer ).buffer;
  26702. passEncoderGPU.setVertexBuffer( i, buffer );
  26703. currentSets.attributes[ i ] = vertexBuffer;
  26704. }
  26705. }
  26706. // occlusion queries - handle multiple consecutive draw calls for an object
  26707. if ( renderContextData.occlusionQuerySet !== undefined ) {
  26708. const lastObject = renderContextData.lastOcclusionObject;
  26709. if ( lastObject !== object ) {
  26710. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  26711. passEncoderGPU.endOcclusionQuery();
  26712. renderContextData.occlusionQueryIndex ++;
  26713. }
  26714. if ( object.occlusionTest === true ) {
  26715. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  26716. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  26717. }
  26718. renderContextData.lastOcclusionObject = object;
  26719. }
  26720. }
  26721. // draw
  26722. if ( object.isBatchedMesh === true ) {
  26723. const starts = object._multiDrawStarts;
  26724. const counts = object._multiDrawCounts;
  26725. const drawCount = object._multiDrawCount;
  26726. const drawInstances = object._multiDrawInstances;
  26727. const bytesPerElement = hasIndex ? index.array.BYTES_PER_ELEMENT : 1;
  26728. for ( let i = 0; i < drawCount; i ++ ) {
  26729. const count = drawInstances ? drawInstances[ i ] : 1;
  26730. const firstInstance = count > 1 ? 0 : i;
  26731. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / bytesPerElement, 0, firstInstance );
  26732. }
  26733. } else if ( hasIndex === true ) {
  26734. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  26735. const indirect = renderObject.getIndirect();
  26736. if ( indirect !== null ) {
  26737. const buffer = this.get( indirect ).buffer;
  26738. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  26739. } else {
  26740. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  26741. }
  26742. info.update( object, indexCount, instanceCount );
  26743. } else {
  26744. const { vertexCount, instanceCount, firstVertex } = drawParams;
  26745. const indirect = renderObject.getIndirect();
  26746. if ( indirect !== null ) {
  26747. const buffer = this.get( indirect ).buffer;
  26748. passEncoderGPU.drawIndirect( buffer, 0 );
  26749. } else {
  26750. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  26751. }
  26752. info.update( object, vertexCount, instanceCount );
  26753. }
  26754. }
  26755. // cache key
  26756. needsRenderUpdate( renderObject ) {
  26757. const data = this.get( renderObject );
  26758. const { object, material } = renderObject;
  26759. const utils = this.utils;
  26760. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  26761. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  26762. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  26763. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  26764. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  26765. let needsUpdate = false;
  26766. if ( data.material !== material || data.materialVersion !== material.version ||
  26767. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  26768. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  26769. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  26770. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  26771. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  26772. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  26773. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  26774. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  26775. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  26776. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  26777. data.primitiveTopology !== primitiveTopology ||
  26778. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  26779. ) {
  26780. data.material = material; data.materialVersion = material.version;
  26781. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  26782. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  26783. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  26784. data.colorWrite = material.colorWrite;
  26785. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  26786. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  26787. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  26788. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  26789. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  26790. data.sampleCount = sampleCount;
  26791. data.colorSpace = colorSpace;
  26792. data.colorFormat = colorFormat;
  26793. data.depthStencilFormat = depthStencilFormat;
  26794. data.primitiveTopology = primitiveTopology;
  26795. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  26796. needsUpdate = true;
  26797. }
  26798. return needsUpdate;
  26799. }
  26800. getRenderCacheKey( renderObject ) {
  26801. const { object, material } = renderObject;
  26802. const utils = this.utils;
  26803. const renderContext = renderObject.context;
  26804. return [
  26805. material.transparent, material.blending, material.premultipliedAlpha,
  26806. material.blendSrc, material.blendDst, material.blendEquation,
  26807. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  26808. material.colorWrite,
  26809. material.depthWrite, material.depthTest, material.depthFunc,
  26810. material.stencilWrite, material.stencilFunc,
  26811. material.stencilFail, material.stencilZFail, material.stencilZPass,
  26812. material.stencilFuncMask, material.stencilWriteMask,
  26813. material.side,
  26814. utils.getSampleCountRenderContext( renderContext ),
  26815. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  26816. utils.getPrimitiveTopology( object, material ),
  26817. renderObject.getGeometryCacheKey(),
  26818. renderObject.clippingContextCacheKey
  26819. ].join();
  26820. }
  26821. // textures
  26822. createSampler( texture ) {
  26823. this.textureUtils.createSampler( texture );
  26824. }
  26825. destroySampler( texture ) {
  26826. this.textureUtils.destroySampler( texture );
  26827. }
  26828. createDefaultTexture( texture ) {
  26829. this.textureUtils.createDefaultTexture( texture );
  26830. }
  26831. createTexture( texture, options ) {
  26832. this.textureUtils.createTexture( texture, options );
  26833. }
  26834. updateTexture( texture, options ) {
  26835. this.textureUtils.updateTexture( texture, options );
  26836. }
  26837. generateMipmaps( texture ) {
  26838. this.textureUtils.generateMipmaps( texture );
  26839. }
  26840. destroyTexture( texture ) {
  26841. this.textureUtils.destroyTexture( texture );
  26842. }
  26843. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  26844. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  26845. }
  26846. initTimestampQuery( renderContext, descriptor ) {
  26847. if ( ! this.trackTimestamp ) return;
  26848. const renderContextData = this.get( renderContext );
  26849. if ( ! renderContextData.timeStampQuerySet ) {
  26850. const type = renderContext.isComputeNode ? 'compute' : 'render';
  26851. const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2, label: `timestamp_${type}_${renderContext.id}` } );
  26852. const timestampWrites = {
  26853. querySet: timeStampQuerySet,
  26854. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  26855. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  26856. };
  26857. Object.assign( descriptor, { timestampWrites } );
  26858. renderContextData.timeStampQuerySet = timeStampQuerySet;
  26859. }
  26860. }
  26861. // timestamp utils
  26862. prepareTimestampBuffer( renderContext, encoder ) {
  26863. if ( ! this.trackTimestamp ) return;
  26864. const renderContextData = this.get( renderContext );
  26865. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  26866. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  26867. renderContextData.currentTimestampQueryBuffers = {
  26868. resolveBuffer: this.device.createBuffer( {
  26869. label: 'timestamp resolve buffer',
  26870. size: size,
  26871. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  26872. } ),
  26873. resultBuffer: this.device.createBuffer( {
  26874. label: 'timestamp result buffer',
  26875. size: size,
  26876. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  26877. } )
  26878. };
  26879. }
  26880. const { resolveBuffer, resultBuffer } = renderContextData.currentTimestampQueryBuffers;
  26881. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  26882. if ( resultBuffer.mapState === 'unmapped' ) {
  26883. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  26884. }
  26885. }
  26886. async resolveTimestampAsync( renderContext, type = 'render' ) {
  26887. if ( ! this.trackTimestamp ) return;
  26888. const renderContextData = this.get( renderContext );
  26889. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  26890. const { resultBuffer } = renderContextData.currentTimestampQueryBuffers;
  26891. await this.device.queue.onSubmittedWorkDone();
  26892. if ( resultBuffer.mapState === 'unmapped' ) {
  26893. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  26894. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  26895. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  26896. this.renderer.info.updateTimestamp( type, duration );
  26897. resultBuffer.unmap();
  26898. } );
  26899. }
  26900. }
  26901. // node builder
  26902. createNodeBuilder( object, renderer ) {
  26903. return new WGSLNodeBuilder( object, renderer );
  26904. }
  26905. // program
  26906. createProgram( program ) {
  26907. const programGPU = this.get( program );
  26908. programGPU.module = {
  26909. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  26910. entryPoint: 'main'
  26911. };
  26912. }
  26913. destroyProgram( program ) {
  26914. this.delete( program );
  26915. }
  26916. // pipelines
  26917. createRenderPipeline( renderObject, promises ) {
  26918. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  26919. }
  26920. createComputePipeline( computePipeline, bindings ) {
  26921. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  26922. }
  26923. beginBundle( renderContext ) {
  26924. const renderContextData = this.get( renderContext );
  26925. renderContextData._currentPass = renderContextData.currentPass;
  26926. renderContextData._currentSets = renderContextData.currentSets;
  26927. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  26928. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  26929. }
  26930. finishBundle( renderContext, bundle ) {
  26931. const renderContextData = this.get( renderContext );
  26932. const bundleEncoder = renderContextData.currentPass;
  26933. const bundleGPU = bundleEncoder.finish();
  26934. this.get( bundle ).bundleGPU = bundleGPU;
  26935. // restore render pass state
  26936. renderContextData.currentSets = renderContextData._currentSets;
  26937. renderContextData.currentPass = renderContextData._currentPass;
  26938. }
  26939. addBundle( renderContext, bundle ) {
  26940. const renderContextData = this.get( renderContext );
  26941. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  26942. }
  26943. // bindings
  26944. createBindings( bindGroup, bindings, cacheIndex, version ) {
  26945. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  26946. }
  26947. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  26948. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  26949. }
  26950. updateBinding( binding ) {
  26951. this.bindingUtils.updateBinding( binding );
  26952. }
  26953. // attributes
  26954. createIndexAttribute( attribute ) {
  26955. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  26956. }
  26957. createAttribute( attribute ) {
  26958. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  26959. }
  26960. createStorageAttribute( attribute ) {
  26961. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  26962. }
  26963. createIndirectStorageAttribute( attribute ) {
  26964. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  26965. }
  26966. updateAttribute( attribute ) {
  26967. this.attributeUtils.updateAttribute( attribute );
  26968. }
  26969. destroyAttribute( attribute ) {
  26970. this.attributeUtils.destroyAttribute( attribute );
  26971. }
  26972. // canvas
  26973. updateSize() {
  26974. this.colorBuffer = this.textureUtils.getColorBuffer();
  26975. this.defaultRenderPassdescriptor = null;
  26976. }
  26977. // utils public
  26978. getMaxAnisotropy() {
  26979. return 16;
  26980. }
  26981. hasFeature( name ) {
  26982. return this.device.features.has( name );
  26983. }
  26984. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  26985. let dstX = 0;
  26986. let dstY = 0;
  26987. let dstLayer = 0;
  26988. let srcX = 0;
  26989. let srcY = 0;
  26990. let srcLayer = 0;
  26991. let srcWidth = srcTexture.image.width;
  26992. let srcHeight = srcTexture.image.height;
  26993. if ( srcRegion !== null ) {
  26994. srcX = srcRegion.x;
  26995. srcY = srcRegion.y;
  26996. srcLayer = srcRegion.z || 0;
  26997. srcWidth = srcRegion.width;
  26998. srcHeight = srcRegion.height;
  26999. }
  27000. if ( dstPosition !== null ) {
  27001. dstX = dstPosition.x;
  27002. dstY = dstPosition.y;
  27003. dstLayer = dstPosition.z || 0;
  27004. }
  27005. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  27006. const sourceGPU = this.get( srcTexture ).texture;
  27007. const destinationGPU = this.get( dstTexture ).texture;
  27008. encoder.copyTextureToTexture(
  27009. {
  27010. texture: sourceGPU,
  27011. mipLevel: level,
  27012. origin: { x: srcX, y: srcY, z: srcLayer }
  27013. },
  27014. {
  27015. texture: destinationGPU,
  27016. mipLevel: level,
  27017. origin: { x: dstX, y: dstY, z: dstLayer }
  27018. },
  27019. [
  27020. srcWidth,
  27021. srcHeight,
  27022. 1
  27023. ]
  27024. );
  27025. this.device.queue.submit( [ encoder.finish() ] );
  27026. }
  27027. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  27028. const renderContextData = this.get( renderContext );
  27029. let sourceGPU = null;
  27030. if ( renderContext.renderTarget ) {
  27031. if ( texture.isDepthTexture ) {
  27032. sourceGPU = this.get( renderContext.depthTexture ).texture;
  27033. } else {
  27034. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  27035. }
  27036. } else {
  27037. if ( texture.isDepthTexture ) {
  27038. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  27039. } else {
  27040. sourceGPU = this.context.getCurrentTexture();
  27041. }
  27042. }
  27043. const destinationGPU = this.get( texture ).texture;
  27044. if ( sourceGPU.format !== destinationGPU.format ) {
  27045. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  27046. return;
  27047. }
  27048. let encoder;
  27049. if ( renderContextData.currentPass ) {
  27050. renderContextData.currentPass.end();
  27051. encoder = renderContextData.encoder;
  27052. } else {
  27053. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  27054. }
  27055. encoder.copyTextureToTexture(
  27056. {
  27057. texture: sourceGPU,
  27058. origin: [ rectangle.x, rectangle.y, 0 ],
  27059. },
  27060. {
  27061. texture: destinationGPU
  27062. },
  27063. [
  27064. rectangle.z,
  27065. rectangle.w
  27066. ]
  27067. );
  27068. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  27069. if ( renderContextData.currentPass ) {
  27070. const { descriptor } = renderContextData;
  27071. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  27072. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  27073. }
  27074. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  27075. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  27076. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  27077. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  27078. if ( renderContext.viewport ) {
  27079. this.updateViewport( renderContext );
  27080. }
  27081. if ( renderContext.scissor ) {
  27082. const { x, y, width, height } = renderContext.scissorValue;
  27083. renderContextData.currentPass.setScissorRect( x, y, width, height );
  27084. }
  27085. } else {
  27086. this.device.queue.submit( [ encoder.finish() ] );
  27087. }
  27088. }
  27089. }
  27090. class IESSpotLight extends SpotLight {
  27091. constructor( color, intensity, distance, angle, penumbra, decay ) {
  27092. super( color, intensity, distance, angle, penumbra, decay );
  27093. this.iesMap = null;
  27094. }
  27095. copy( source, recursive ) {
  27096. super.copy( source, recursive );
  27097. this.iesMap = source.iesMap;
  27098. return this;
  27099. }
  27100. }
  27101. class StandardNodeLibrary extends NodeLibrary {
  27102. constructor() {
  27103. super();
  27104. this.addMaterial( MeshPhongNodeMaterial, 'MeshPhongMaterial' );
  27105. this.addMaterial( MeshStandardNodeMaterial, 'MeshStandardMaterial' );
  27106. this.addMaterial( MeshPhysicalNodeMaterial, 'MeshPhysicalMaterial' );
  27107. this.addMaterial( MeshToonNodeMaterial, 'MeshToonMaterial' );
  27108. this.addMaterial( MeshBasicNodeMaterial, 'MeshBasicMaterial' );
  27109. this.addMaterial( MeshLambertNodeMaterial, 'MeshLambertMaterial' );
  27110. this.addMaterial( MeshNormalNodeMaterial, 'MeshNormalMaterial' );
  27111. this.addMaterial( MeshMatcapNodeMaterial, 'MeshMatcapMaterial' );
  27112. this.addMaterial( LineBasicNodeMaterial, 'LineBasicMaterial' );
  27113. this.addMaterial( LineDashedNodeMaterial, 'LineDashedMaterial' );
  27114. this.addMaterial( PointsNodeMaterial, 'PointsMaterial' );
  27115. this.addMaterial( SpriteNodeMaterial, 'SpriteMaterial' );
  27116. this.addMaterial( ShadowNodeMaterial, 'ShadowMaterial' );
  27117. this.addLight( PointLightNode, PointLight );
  27118. this.addLight( DirectionalLightNode, DirectionalLight );
  27119. this.addLight( RectAreaLightNode, RectAreaLight );
  27120. this.addLight( SpotLightNode, SpotLight );
  27121. this.addLight( AmbientLightNode, AmbientLight );
  27122. this.addLight( HemisphereLightNode, HemisphereLight );
  27123. this.addLight( LightProbeNode, LightProbe );
  27124. this.addLight( IESSpotLightNode, IESSpotLight );
  27125. this.addToneMapping( linearToneMapping, LinearToneMapping );
  27126. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  27127. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  27128. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  27129. this.addToneMapping( agxToneMapping, AgXToneMapping );
  27130. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  27131. }
  27132. }
  27133. /*
  27134. const debugHandler = {
  27135. get: function ( target, name ) {
  27136. // Add |update
  27137. if ( /^(create|destroy)/.test( name ) ) console.log( 'WebGPUBackend.' + name );
  27138. return target[ name ];
  27139. }
  27140. };
  27141. */
  27142. class WebGPURenderer extends Renderer {
  27143. constructor( parameters = {} ) {
  27144. let BackendClass;
  27145. if ( parameters.forceWebGL ) {
  27146. BackendClass = WebGLBackend;
  27147. } else {
  27148. BackendClass = WebGPUBackend;
  27149. parameters.getFallback = () => {
  27150. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  27151. return new WebGLBackend( parameters );
  27152. };
  27153. }
  27154. const backend = new BackendClass( parameters );
  27155. //super( new Proxy( backend, debugHandler ) );
  27156. super( backend, parameters );
  27157. this.library = new StandardNodeLibrary();
  27158. this.isWebGPURenderer = true;
  27159. }
  27160. }
  27161. class BundleGroup extends Group {
  27162. constructor() {
  27163. super();
  27164. this.isBundleGroup = true;
  27165. this.type = 'BundleGroup';
  27166. this.static = true;
  27167. this.version = 0;
  27168. }
  27169. set needsUpdate( value ) {
  27170. if ( value === true ) this.version ++;
  27171. }
  27172. }
  27173. const _material = /*@__PURE__*/ new NodeMaterial();
  27174. const _quadMesh = /*@__PURE__*/ new QuadMesh( _material );
  27175. class PostProcessing {
  27176. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  27177. this.renderer = renderer;
  27178. this.outputNode = outputNode;
  27179. this.outputColorTransform = true;
  27180. this.needsUpdate = true;
  27181. _material.name = 'PostProcessing';
  27182. }
  27183. render() {
  27184. this.update();
  27185. const renderer = this.renderer;
  27186. const toneMapping = renderer.toneMapping;
  27187. const outputColorSpace = renderer.outputColorSpace;
  27188. renderer.toneMapping = NoToneMapping;
  27189. renderer.outputColorSpace = LinearSRGBColorSpace;
  27190. //
  27191. _quadMesh.render( renderer );
  27192. //
  27193. renderer.toneMapping = toneMapping;
  27194. renderer.outputColorSpace = outputColorSpace;
  27195. }
  27196. update() {
  27197. if ( this.needsUpdate === true ) {
  27198. const renderer = this.renderer;
  27199. const toneMapping = renderer.toneMapping;
  27200. const outputColorSpace = renderer.outputColorSpace;
  27201. _quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  27202. _quadMesh.material.needsUpdate = true;
  27203. this.needsUpdate = false;
  27204. }
  27205. }
  27206. async renderAsync() {
  27207. this.update();
  27208. const renderer = this.renderer;
  27209. const toneMapping = renderer.toneMapping;
  27210. const outputColorSpace = renderer.outputColorSpace;
  27211. renderer.toneMapping = NoToneMapping;
  27212. renderer.outputColorSpace = LinearSRGBColorSpace;
  27213. //
  27214. await _quadMesh.renderAsync( renderer );
  27215. //
  27216. renderer.toneMapping = toneMapping;
  27217. renderer.outputColorSpace = outputColorSpace;
  27218. }
  27219. }
  27220. // renderer state
  27221. function saveRendererState( renderer, state = {} ) {
  27222. state.toneMapping = renderer.toneMapping;
  27223. state.toneMappingExposure = renderer.toneMappingExposure;
  27224. state.outputColorSpace = renderer.outputColorSpace;
  27225. state.renderTarget = renderer.getRenderTarget();
  27226. state.activeCubeFace = renderer.getActiveCubeFace();
  27227. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  27228. state.renderObjectFunction = renderer.getRenderObjectFunction();
  27229. state.pixelRatio = renderer.getPixelRatio();
  27230. state.mrt = renderer.getMRT();
  27231. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  27232. state.clearAlpha = renderer.getClearAlpha();
  27233. state.autoClear = renderer.autoClear;
  27234. state.scissorTest = renderer.getScissorTest();
  27235. return state;
  27236. }
  27237. function resetRendererState( renderer, state ) {
  27238. state = saveRendererState( renderer, state );
  27239. renderer.setMRT( null );
  27240. renderer.setRenderObjectFunction( null );
  27241. renderer.setClearColor( 0x000000, 1 );
  27242. renderer.autoClear = true;
  27243. return state;
  27244. }
  27245. function restoreRendererState( renderer, state ) {
  27246. renderer.toneMapping = state.toneMapping;
  27247. renderer.toneMappingExposure = state.toneMappingExposure;
  27248. renderer.outputColorSpace = state.outputColorSpace;
  27249. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  27250. renderer.setRenderObjectFunction( state.renderObjectFunction );
  27251. renderer.setPixelRatio( state.pixelRatio );
  27252. renderer.setMRT( state.mrt );
  27253. renderer.setClearColor( state.clearColor, state.clearAlpha );
  27254. renderer.autoClear = state.autoClear;
  27255. renderer.setScissorTest( state.scissorTest );
  27256. }
  27257. // renderer and scene state
  27258. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  27259. state = saveRendererState( renderer, state );
  27260. state.background = scene.background;
  27261. state.backgroundNode = scene.backgroundNode;
  27262. state.overrideMaterial = scene.overrideMaterial;
  27263. return state;
  27264. }
  27265. function resetRendererAndSceneState( renderer, scene, state ) {
  27266. state = saveRendererAndSceneState( renderer, scene, state );
  27267. scene.background = null;
  27268. scene.backgroundNode = null;
  27269. scene.overrideMaterial = null;
  27270. return state;
  27271. }
  27272. function restoreRendererAndSceneState( renderer, scene, state ) {
  27273. restoreRendererState( renderer, state );
  27274. scene.background = state.background;
  27275. scene.backgroundNode = state.backgroundNode;
  27276. scene.overrideMaterial = state.overrideMaterial;
  27277. }
  27278. var PostProcessingUtils = /*#__PURE__*/Object.freeze({
  27279. __proto__: null,
  27280. resetRendererAndSceneState: resetRendererAndSceneState,
  27281. resetRendererState: resetRendererState,
  27282. restoreRendererAndSceneState: restoreRendererAndSceneState,
  27283. restoreRendererState: restoreRendererState,
  27284. saveRendererAndSceneState: saveRendererAndSceneState,
  27285. saveRendererState: saveRendererState
  27286. });
  27287. class StorageTexture extends Texture {
  27288. constructor( width = 1, height = 1 ) {
  27289. super();
  27290. this.image = { width, height };
  27291. this.magFilter = LinearFilter;
  27292. this.minFilter = LinearFilter;
  27293. this.isStorageTexture = true;
  27294. }
  27295. }
  27296. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  27297. constructor( array, itemSize ) {
  27298. super( array, itemSize, Uint32Array );
  27299. this.isIndirectStorageBufferAttribute = true;
  27300. }
  27301. }
  27302. class NodeLoader extends Loader {
  27303. constructor( manager ) {
  27304. super( manager );
  27305. this.textures = {};
  27306. this.nodes = {};
  27307. }
  27308. load( url, onLoad, onProgress, onError ) {
  27309. const loader = new FileLoader( this.manager );
  27310. loader.setPath( this.path );
  27311. loader.setRequestHeader( this.requestHeader );
  27312. loader.setWithCredentials( this.withCredentials );
  27313. loader.load( url, ( text ) => {
  27314. try {
  27315. onLoad( this.parse( JSON.parse( text ) ) );
  27316. } catch ( e ) {
  27317. if ( onError ) {
  27318. onError( e );
  27319. } else {
  27320. console.error( e );
  27321. }
  27322. this.manager.itemError( url );
  27323. }
  27324. }, onProgress, onError );
  27325. }
  27326. parseNodes( json ) {
  27327. const nodes = {};
  27328. if ( json !== undefined ) {
  27329. for ( const nodeJSON of json ) {
  27330. const { uuid, type } = nodeJSON;
  27331. nodes[ uuid ] = this.createNodeFromType( type );
  27332. nodes[ uuid ].uuid = uuid;
  27333. }
  27334. const meta = { nodes, textures: this.textures };
  27335. for ( const nodeJSON of json ) {
  27336. nodeJSON.meta = meta;
  27337. const node = nodes[ nodeJSON.uuid ];
  27338. node.deserialize( nodeJSON );
  27339. delete nodeJSON.meta;
  27340. }
  27341. }
  27342. return nodes;
  27343. }
  27344. parse( json ) {
  27345. const node = this.createNodeFromType( json.type );
  27346. node.uuid = json.uuid;
  27347. const nodes = this.parseNodes( json.nodes );
  27348. const meta = { nodes, textures: this.textures };
  27349. json.meta = meta;
  27350. node.deserialize( json );
  27351. delete json.meta;
  27352. return node;
  27353. }
  27354. setTextures( value ) {
  27355. this.textures = value;
  27356. return this;
  27357. }
  27358. setNodes( value ) {
  27359. this.nodes = value;
  27360. return this;
  27361. }
  27362. createNodeFromType( type ) {
  27363. if ( this.nodes[ type ] === undefined ) {
  27364. console.error( 'THREE.NodeLoader: Node type not found:', type );
  27365. return float();
  27366. }
  27367. return nodeObject( new this.nodes[ type ]() );
  27368. }
  27369. }
  27370. class NodeMaterialLoader extends MaterialLoader {
  27371. constructor( manager ) {
  27372. super( manager );
  27373. this.nodes = {};
  27374. this.nodeMaterials = {};
  27375. }
  27376. parse( json ) {
  27377. const material = super.parse( json );
  27378. const nodes = this.nodes;
  27379. const inputNodes = json.inputNodes;
  27380. for ( const property in inputNodes ) {
  27381. const uuid = inputNodes[ property ];
  27382. material[ property ] = nodes[ uuid ];
  27383. }
  27384. return material;
  27385. }
  27386. setNodes( value ) {
  27387. this.nodes = value;
  27388. return this;
  27389. }
  27390. setNodeMaterials( value ) {
  27391. this.nodeMaterials = value;
  27392. return this;
  27393. }
  27394. createMaterialFromType( type ) {
  27395. const materialClass = this.nodeMaterials[ type ];
  27396. if ( materialClass !== undefined ) {
  27397. return new materialClass();
  27398. }
  27399. return super.createMaterialFromType( type );
  27400. }
  27401. }
  27402. class NodeObjectLoader extends ObjectLoader {
  27403. constructor( manager ) {
  27404. super( manager );
  27405. this.nodes = {};
  27406. this.nodeMaterials = {};
  27407. this._nodesJSON = null;
  27408. }
  27409. setNodes( value ) {
  27410. this.nodes = value;
  27411. return this;
  27412. }
  27413. setNodeMaterials( value ) {
  27414. this.nodeMaterials = value;
  27415. return this;
  27416. }
  27417. parse( json, onLoad ) {
  27418. this._nodesJSON = json.nodes;
  27419. const data = super.parse( json, onLoad );
  27420. this._nodesJSON = null; // dispose
  27421. return data;
  27422. }
  27423. parseNodes( json, textures ) {
  27424. if ( json !== undefined ) {
  27425. const loader = new NodeLoader();
  27426. loader.setNodes( this.nodes );
  27427. loader.setTextures( textures );
  27428. return loader.parseNodes( json );
  27429. }
  27430. return {};
  27431. }
  27432. parseMaterials( json, textures ) {
  27433. const materials = {};
  27434. if ( json !== undefined ) {
  27435. const nodes = this.parseNodes( this._nodesJSON, textures );
  27436. const loader = new NodeMaterialLoader();
  27437. loader.setTextures( textures );
  27438. loader.setNodes( nodes );
  27439. loader.setNodeMaterials( this.nodeMaterials );
  27440. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27441. const data = json[ i ];
  27442. materials[ data.uuid ] = loader.parse( data );
  27443. }
  27444. }
  27445. return materials;
  27446. }
  27447. }
  27448. class ClippingGroup extends Group {
  27449. constructor() {
  27450. super();
  27451. this.isClippingGroup = true;
  27452. this.clippingPlanes = [];
  27453. this.enabled = true;
  27454. this.clipIntersection = false;
  27455. this.clipShadows = false;
  27456. }
  27457. }
  27458. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayElementNode, AssignNode, AttributeNode, BackSide, BasicEnvironmentNode, BasicShadowMap, BatchNode, BoxGeometry, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, CacheNode, CineonToneMapping, ClampToEdgeWrapping, ClippingGroup, CodeNode, Color, ColorManagement, ColorSpaceNode, ComputeNode, ConstNode, ContextNode, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureNode, CubeUVReflectionMapping, CullFaceBack, CullFaceFront, CullFaceNone, CustomBlending, DataArrayTexture, DataTexture, DecrementStencilOp, DecrementWrapStencilOp, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightNode, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicDrawUsage, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectUVNode, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExpressionNode, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, FogExp2Node, FogNode, FogRangeNode, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, Group, HalfFloatType, HemisphereLight, HemisphereLightNode, IESSpotLight, IESSpotLightNode, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, InstanceNode, InstancedBufferAttribute, InstancedInterleavedBuffer, InstancedMeshNode, InstancedPointsNodeMaterial, IntType, InterleavedBuffer, InterleavedBufferAttribute, InvertStencilOp, IrradianceNode, JoinNode, KeepStencilOp, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, LightProbe, LightProbeNode, Lighting, LightingContextNode, LightingModel, LightingNode, LightsNode, Line2NodeMaterial, LineBasicMaterial, LineBasicNodeMaterial, LineDashedMaterial, LineDashedNodeMaterial, LinearFilter, LinearMipMapLinearFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, Loader, LoopNode, LuminanceAlphaFormat, LuminanceFormat, MRTNode, MatcapUVNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathUtils, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, 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, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAccess, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, OutputStructNode, PCFShadowMap, PMREMGenerator, PMREMNode, ParameterNode, PassNode, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PointLight, PointLightNode, PointUVNode, PointsMaterial, PointsNodeMaterial, PostProcessing, PostProcessingUtils, PosterizeNode, PropertyNode, QuadMesh, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, 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, RGBFormat, RGBIntegerFormat, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RendererReferenceNode, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, ScreenNode, ScriptableNode, ScriptableValueNode, SetNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, ShortType, SkinningNode, SphereGeometry, SplitNode, SpotLight, SpotLightNode, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticDrawUsage, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, TriplanarTexturesNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, shaderStages, vectorComponents };
粤ICP备19079148号