three.webgpu.js 2.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592885938859488595885968859788598885998860088601886028860388604886058860688607886088860988610886118861288613886148861588616886178861888619886208862188622886238862488625886268862788628886298863088631886328863388634886358863688637886388863988640886418864288643886448864588646886478864888649886508865188652886538865488655886568865788658886598866088661886628866388664886658866688667886688866988670
  1. /**
  2. * @license
  3. * Copyright 2010-2026 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. import { Color, Vector2, Vector3, Vector4, Matrix2, Matrix3, Matrix4, UnsignedIntType, IntType, error, RedFormat, RedIntegerFormat, DepthFormat, DepthStencilFormat, AlphaFormat, RGFormat, RGIntegerFormat, RGBFormat, RGBIntegerFormat, EventDispatcher, MathUtils, warn, WebGLCoordinateSystem, WebGPUCoordinateSystem, ColorManagement, SRGBTransfer, NoToneMapping, StaticDrawUsage, InterleavedBufferAttribute, InterleavedBuffer, DynamicDrawUsage, NoColorSpace, log as log$1, warnOnce, Texture, Compatibility, LessCompare, LessEqualCompare, GreaterCompare, GreaterEqualCompare, NearestFilter, Sphere, BackSide, DoubleSide, CubeTexture, CubeReflectionMapping, CubeRefractionMapping, TangentSpaceNormalMap, NoNormalPacking, NormalRGPacking, NormalGAPacking, ObjectSpaceNormalMap, RED_GREEN_RGTC2_Format, RG11_EAC_Format, InstancedBufferAttribute, InstancedInterleavedBuffer, DataArrayTexture, FloatType, FramebufferTexture, LinearMipmapLinearFilter, DepthTexture, Material, LineBasicMaterial, LineDashedMaterial, NoBlending, MeshNormalMaterial, SRGBColorSpace, RenderTarget, BoxGeometry, Mesh, Scene, LinearFilter, CubeCamera, EquirectangularReflectionMapping, EquirectangularRefractionMapping, AddOperation, MixOperation, MultiplyOperation, MeshBasicMaterial, MeshLambertMaterial, MeshPhongMaterial, DataTexture, HalfFloatType, ClampToEdgeWrapping, BufferGeometry, OrthographicCamera, PerspectiveCamera, LinearSRGBColorSpace, RGBAFormat, CubeUVReflectionMapping, BufferAttribute, MeshStandardMaterial, MeshPhysicalMaterial, MeshToonMaterial, MeshMatcapMaterial, SpriteMaterial, PointsMaterial, ShadowMaterial, Uint32BufferAttribute, Uint16BufferAttribute, ByteType, UnsignedByteType, ShortType, UnsignedShortType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedInt248Type, UnsignedInt5999Type, UnsignedInt101111Type, NormalBlending, SrcAlphaFactor, OneMinusSrcAlphaFactor, AddEquation, MaterialBlending, Object3D, LinearMipMapLinearFilter, Plane, Float32BufferAttribute, UVMapping, PCFShadowMap, VSMShadowMap, BasicShadowMap, CubeDepthTexture, SphereGeometry, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, yieldToMain, REVISION, ArrayCamera, PlaneGeometry, FrontSide, CustomBlending, ZeroFactor, CylinderGeometry, Quaternion, WebXRController, RAD2DEG, PCFSoftShadowMap, FrustumArray, Frustum, RGBAIntegerFormat, TimestampQuery, createCanvasElement, ReverseSubtractEquation, SubtractEquation, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcColorFactor, DstAlphaFactor, DstColorFactor, SrcAlphaSaturateFactor, SrcColorFactor, OneFactor, CullFaceNone, CullFaceBack, CullFaceFront, MultiplyBlending, SubtractiveBlending, AdditiveBlending, NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessEqualDepth, LessDepth, AlwaysDepth, NeverDepth, ReversedDepthFuncs, 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, R11_EAC_Format, SIGNED_R11_EAC_Format, SIGNED_RG11_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, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RED_RGTC1_Format, SIGNED_RED_RGTC1_Format, SIGNED_RED_GREEN_RGTC2_Format, MirroredRepeatWrapping, RepeatWrapping, NearestMipmapNearestFilter, NotEqualCompare, EqualCompare, AlwaysCompare, NeverCompare, LinearTransfer, getByteLength, isTypedArray, 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, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BasicDepthPacking, BatchedMesh, BezierInterpolant, 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, Cylindrical, Data3DTexture, DataTextureLoader, DataUtils, DefaultLoadingManager, DetachedBindMode, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DynamicCopyUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, Euler, ExternalTexture, ExtrudeGeometry, Fog, FogExp2, GLBufferAttribute, GLSL1, GLSL3, GridHelper, HTMLTexture, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, InstancedBufferGeometry, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, Interpolant, InterpolateBezier, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InterpolationSamplingMode, InterpolationSamplingType, KeyframeTrack, LOD, LatheGeometry, Layers, Light, Line, Line3, LineCurve, LineCurve3, LineLoop, LineSegments, LinearInterpolant, LinearMipMapNearestFilter, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, MeshDepthMaterial, MeshDistanceMaterial, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NormalAnimationBlendMode, NumberKeyframeTrack, OctahedronGeometry, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, Path, PlaneHelper, PointLightHelper, Points, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGDepthPacking, RawShaderMaterial, Ray, Raycaster, RenderTarget3D, RingGeometry, ShaderMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Spherical, SphericalHarmonics3, SplineCurve, SpotLightHelper, Sprite, StaticCopyUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, TOUCH, TetrahedronGeometry, TextureLoader, TextureUtils, Timer, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLRenderTarget, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding, getConsoleFunction, setConsoleFunction } from './three.core.js';
  8. const refreshUniforms = [
  9. 'alphaMap',
  10. 'alphaTest',
  11. 'anisotropy',
  12. 'anisotropyMap',
  13. 'anisotropyRotation',
  14. 'aoMap',
  15. 'aoMapIntensity',
  16. 'attenuationColor',
  17. 'attenuationDistance',
  18. 'bumpMap',
  19. 'clearcoat',
  20. 'clearcoatMap',
  21. 'clearcoatNormalMap',
  22. 'clearcoatNormalScale',
  23. 'clearcoatRoughness',
  24. 'color',
  25. 'dispersion',
  26. 'displacementMap',
  27. 'emissive',
  28. 'emissiveIntensity',
  29. 'emissiveMap',
  30. 'envMap',
  31. 'envMapIntensity',
  32. 'envMapRotation',
  33. 'gradientMap',
  34. 'ior',
  35. 'iridescence',
  36. 'iridescenceIOR',
  37. 'iridescenceMap',
  38. 'iridescenceThicknessMap',
  39. 'lightMap',
  40. 'lightMapIntensity',
  41. 'map',
  42. 'matcap',
  43. 'metalness',
  44. 'metalnessMap',
  45. 'normalMap',
  46. 'normalScale',
  47. 'opacity',
  48. 'roughness',
  49. 'roughnessMap',
  50. 'sheen',
  51. 'sheenColor',
  52. 'sheenColorMap',
  53. 'sheenRoughnessMap',
  54. 'shininess',
  55. 'specular',
  56. 'specularColor',
  57. 'specularColorMap',
  58. 'specularIntensity',
  59. 'specularIntensityMap',
  60. 'specularMap',
  61. 'thickness',
  62. 'transmission',
  63. 'transmissionMap'
  64. ];
  65. /**
  66. * A WeakMap to cache lights data for node materials.
  67. * Cache lights data by render ID to avoid unnecessary recalculations.
  68. *
  69. * @private
  70. * @type {WeakMap<LightsNode,Object>}
  71. */
  72. const _lightsCache = new WeakMap();
  73. /**
  74. * Holds the material data for comparison.
  75. *
  76. * @private
  77. * @type {WeakMap<Material,Object>}
  78. */
  79. const _materialCache = new WeakMap();
  80. /**
  81. * Holds the geometry data for comparison.
  82. *
  83. * @private
  84. * @type {WeakMap<BufferGeometry,Object>}
  85. */
  86. const _geometryCache = new WeakMap();
  87. /**
  88. * This class is used by {@link WebGPURenderer} as management component.
  89. * It's primary purpose is to determine whether render objects require a
  90. * refresh right before they are going to be rendered or not.
  91. */
  92. class NodeMaterialObserver {
  93. /**
  94. * Constructs a new node material observer.
  95. *
  96. * @param {NodeBuilder} builder - The node builder.
  97. */
  98. constructor( builder ) {
  99. /**
  100. * A node material can be used by more than one render object so the
  101. * monitor must maintain a list of render objects.
  102. *
  103. * @type {WeakMap<RenderObject,Object>}
  104. */
  105. this.renderObjects = new WeakMap();
  106. /**
  107. * Whether the material uses node objects or not.
  108. *
  109. * @type {boolean}
  110. */
  111. this.hasNode = this.containsNode( builder );
  112. /**
  113. * Whether the node builder's 3D object is animated or not.
  114. *
  115. * @type {boolean}
  116. */
  117. this.hasAnimation = builder.object.isSkinnedMesh === true;
  118. /**
  119. * A list of all possible material uniforms
  120. *
  121. * @type {Array<string>}
  122. */
  123. this.refreshUniforms = refreshUniforms;
  124. /**
  125. * Holds the current render ID from the node frame.
  126. *
  127. * @type {number}
  128. * @default 0
  129. */
  130. this.renderId = 0;
  131. }
  132. /**
  133. * Returns `true` if the given render object is verified for the first time of this observer.
  134. *
  135. * @param {RenderObject} renderObject - The render object.
  136. * @return {boolean} Whether the given render object is verified for the first time of this observer.
  137. */
  138. firstInitialization( renderObject ) {
  139. const hasInitialized = this.renderObjects.has( renderObject );
  140. if ( hasInitialized === false ) {
  141. this.getRenderObjectData( renderObject );
  142. return true;
  143. }
  144. return false;
  145. }
  146. /**
  147. * Returns `true` if the current rendering produces motion vectors.
  148. *
  149. * @param {Renderer} renderer - The renderer.
  150. * @return {boolean} Whether the current rendering produces motion vectors or not.
  151. */
  152. needsVelocity( renderer ) {
  153. const mrt = renderer.getMRT();
  154. return ( mrt !== null && mrt.has( 'velocity' ) );
  155. }
  156. /**
  157. * Returns monitoring data for the given render object.
  158. *
  159. * @param {RenderObject} renderObject - The render object.
  160. * @return {Object} The monitoring data.
  161. */
  162. getRenderObjectData( renderObject ) {
  163. let data = this.renderObjects.get( renderObject );
  164. if ( data === undefined ) {
  165. const { geometry, object } = renderObject;
  166. data = {
  167. geometryId: geometry.id,
  168. worldMatrix: object.matrixWorld.clone()
  169. };
  170. if ( object.center ) {
  171. data.center = object.center.clone();
  172. }
  173. if ( object.morphTargetInfluences ) {
  174. data.morphTargetInfluences = object.morphTargetInfluences.slice();
  175. }
  176. if ( renderObject.bundle !== null ) {
  177. data.version = renderObject.bundle.version;
  178. }
  179. if ( renderObject.material.transmission > 0 ) {
  180. const { width, height } = renderObject.context;
  181. data.bufferWidth = width;
  182. data.bufferHeight = height;
  183. }
  184. const { environmentIntensity, environmentRotation } = renderObject.scene;
  185. data.environmentIntensity = environmentIntensity;
  186. data.environmentRotation = environmentRotation.clone();
  187. data.lights = this.getLightsData( renderObject.lightsNode.getBuiltinLights(), [] );
  188. this.renderObjects.set( renderObject, data );
  189. }
  190. return data;
  191. }
  192. /**
  193. * Returns an attribute data structure holding the attributes versions for
  194. * monitoring.
  195. *
  196. * @param {Object} attributes - The geometry attributes.
  197. * @return {Object} An object for monitoring the versions of attributes.
  198. */
  199. getAttributesData( attributes ) {
  200. const attributesData = {};
  201. for ( const name in attributes ) {
  202. const attribute = attributes[ name ];
  203. attributesData[ name ] = {
  204. id: attribute.isInterleavedBufferAttribute ? attribute.data.uuid : attribute.id,
  205. version: attribute.isInterleavedBufferAttribute ? attribute.data.version : attribute.version,
  206. };
  207. }
  208. return attributesData;
  209. }
  210. /**
  211. * Returns `true` if the node builder's material uses
  212. * node properties.
  213. *
  214. * @param {NodeBuilder} builder - The current node builder.
  215. * @return {boolean} Whether the node builder's material uses node properties or not.
  216. */
  217. containsNode( builder ) {
  218. const material = builder.material;
  219. for ( const property in material ) {
  220. if ( material[ property ] && material[ property ].isNode )
  221. return true;
  222. }
  223. if ( builder.context.modelViewMatrix || builder.context.modelNormalViewMatrix || builder.context.getAO || builder.context.getShadow )
  224. return true;
  225. return false;
  226. }
  227. /**
  228. * Returns a geometry data structure holding the geometry property values for
  229. * monitoring.
  230. *
  231. * @param {BufferGeometry} geometry - The geometry.
  232. * @return {Object} An object for monitoring geometry properties.
  233. */
  234. getGeometryData( geometry ) {
  235. let data = _geometryCache.get( geometry );
  236. if ( data === undefined ) {
  237. data = {
  238. _renderId: -1,
  239. _equal: false,
  240. attributes: this.getAttributesData( geometry.attributes ),
  241. indexId: geometry.index ? geometry.index.id : null,
  242. indexVersion: geometry.index ? geometry.index.version : null,
  243. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  244. };
  245. _geometryCache.set( geometry, data );
  246. }
  247. return data;
  248. }
  249. /**
  250. * Returns a material data structure holding the material property values for
  251. * monitoring.
  252. *
  253. * @param {Material} material - The material.
  254. * @return {Object} An object for monitoring material properties.
  255. */
  256. getMaterialData( material ) {
  257. let data = _materialCache.get( material );
  258. if ( data === undefined ) {
  259. data = { _renderId: -1, _equal: false };
  260. for ( const property of this.refreshUniforms ) {
  261. const value = material[ property ];
  262. if ( value === null || value === undefined ) continue;
  263. if ( typeof value === 'object' && value.clone !== undefined ) {
  264. if ( value.isTexture === true ) {
  265. data[ property ] = { id: value.id, version: 0 };
  266. } else {
  267. data[ property ] = value.clone();
  268. }
  269. } else {
  270. data[ property ] = value;
  271. }
  272. }
  273. _materialCache.set( material, data );
  274. }
  275. return data;
  276. }
  277. /**
  278. * Returns `true` if the given render object has not changed its state.
  279. *
  280. * @param {RenderObject} renderObject - The render object.
  281. * @param {Array<Light>} lightsData - The current material lights.
  282. * @param {number} renderId - The current render ID.
  283. * @return {boolean} Whether the given render object is equal to its cached state or not.
  284. */
  285. equals( renderObject, lightsData, renderId ) {
  286. const { object, material, geometry } = renderObject;
  287. const renderObjectData = this.getRenderObjectData( renderObject );
  288. // world matrix
  289. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  290. renderObjectData.worldMatrix.copy( object.matrixWorld );
  291. return false;
  292. }
  293. // material
  294. const materialData = this.getMaterialData( renderObject.material );
  295. // check the material for the "equal" state just once per render for all render objects
  296. if ( materialData._renderId !== renderId ) {
  297. materialData._renderId = renderId;
  298. for ( const property in materialData ) {
  299. const value = materialData[ property ];
  300. const mtlValue = material[ property ];
  301. if ( property === '_renderId' ) continue;
  302. if ( property === '_equal' ) continue;
  303. if ( value.equals !== undefined ) {
  304. if ( value.equals( mtlValue ) === false ) {
  305. value.copy( mtlValue );
  306. materialData._equal = false;
  307. return false;
  308. }
  309. } else if ( mtlValue.isTexture === true ) {
  310. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  311. value.id = mtlValue.id;
  312. value.version = mtlValue.version;
  313. materialData._equal = false;
  314. return false;
  315. }
  316. } else if ( value !== mtlValue ) {
  317. materialData[ property ] = mtlValue;
  318. materialData._equal = false;
  319. return false;
  320. }
  321. }
  322. if ( materialData.transmission > 0 ) {
  323. const { width, height } = renderObject.context;
  324. if ( renderObjectData.bufferWidth !== width || renderObjectData.bufferHeight !== height ) {
  325. renderObjectData.bufferWidth = width;
  326. renderObjectData.bufferHeight = height;
  327. materialData._equal = false;
  328. return false;
  329. }
  330. }
  331. materialData._equal = true;
  332. } else {
  333. if ( materialData._equal === false ) return false;
  334. }
  335. // geometry
  336. if ( renderObjectData.geometryId !== geometry.id ) {
  337. renderObjectData.geometryId = geometry.id;
  338. return false;
  339. }
  340. const geometryData = this.getGeometryData( renderObject.geometry );
  341. // check the geoemtry for the "equal" state just once per render for all render objects
  342. if ( geometryData._renderId !== renderId ) {
  343. geometryData._renderId = renderId;
  344. // attributes
  345. const attributes = geometry.attributes;
  346. const storedAttributes = geometryData.attributes;
  347. let currentAttributeCount = 0;
  348. let storedAttributeCount = 0;
  349. for ( const _ in attributes ) currentAttributeCount ++; // eslint-disable-line no-unused-vars
  350. for ( const name in storedAttributes ) {
  351. storedAttributeCount ++;
  352. const storedAttributeData = storedAttributes[ name ];
  353. const attribute = attributes[ name ];
  354. if ( attribute === undefined ) {
  355. // attribute was removed
  356. delete storedAttributes[ name ];
  357. geometryData._equal = false;
  358. return false;
  359. }
  360. const id = attribute.isInterleavedBufferAttribute ? attribute.data.uuid : attribute.id;
  361. const version = attribute.isInterleavedBufferAttribute ? attribute.data.version : attribute.version;
  362. if ( storedAttributeData.id !== id || storedAttributeData.version !== version ) {
  363. storedAttributeData.id = id;
  364. storedAttributeData.version = version;
  365. geometryData._equal = false;
  366. return false;
  367. }
  368. }
  369. if ( storedAttributeCount !== currentAttributeCount ) {
  370. geometryData.attributes = this.getAttributesData( attributes );
  371. geometryData._equal = false;
  372. return false;
  373. }
  374. // check index
  375. const index = geometry.index;
  376. const storedIndexId = geometryData.indexId;
  377. const storedIndexVersion = geometryData.indexVersion;
  378. const currentIndexId = index ? index.id : null;
  379. const currentIndexVersion = index ? index.version : null;
  380. if ( storedIndexId !== currentIndexId || storedIndexVersion !== currentIndexVersion ) {
  381. geometryData.indexId = currentIndexId;
  382. geometryData.indexVersion = currentIndexVersion;
  383. geometryData._equal = false;
  384. return false;
  385. }
  386. // check drawRange
  387. if ( geometryData.drawRange.start !== geometry.drawRange.start || geometryData.drawRange.count !== geometry.drawRange.count ) {
  388. geometryData.drawRange.start = geometry.drawRange.start;
  389. geometryData.drawRange.count = geometry.drawRange.count;
  390. geometryData._equal = false;
  391. return false;
  392. }
  393. geometryData._equal = true;
  394. } else {
  395. if ( geometryData._equal === false ) return false;
  396. }
  397. // morph targets
  398. if ( renderObjectData.morphTargetInfluences ) {
  399. let morphChanged = false;
  400. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  401. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  402. renderObjectData.morphTargetInfluences[ i ] = object.morphTargetInfluences[ i ];
  403. morphChanged = true;
  404. }
  405. }
  406. if ( morphChanged ) return false;
  407. }
  408. // lights
  409. if ( renderObjectData.lights ) {
  410. for ( let i = 0; i < lightsData.length; i ++ ) {
  411. if ( renderObjectData.lights[ i ].map !== lightsData[ i ].map ) {
  412. return false;
  413. }
  414. }
  415. }
  416. // scene
  417. const scene = renderObject.scene;
  418. if ( scene.environment !== null && material.envMap === null ) {
  419. if ( renderObjectData.environmentIntensity !== scene.environmentIntensity ||
  420. renderObjectData.environmentRotation.equals( scene.environmentRotation ) === false ) {
  421. renderObjectData.environmentIntensity = scene.environmentIntensity;
  422. renderObjectData.environmentRotation.copy( scene.environmentRotation );
  423. return false;
  424. }
  425. }
  426. // center
  427. if ( renderObjectData.center ) {
  428. if ( renderObjectData.center.equals( object.center ) === false ) {
  429. renderObjectData.center.copy( object.center );
  430. return false;
  431. }
  432. }
  433. // bundle
  434. if ( renderObject.bundle !== null ) {
  435. renderObjectData.version = renderObject.bundle.version;
  436. }
  437. return true;
  438. }
  439. /**
  440. * Returns the lights data for the given material lights.
  441. *
  442. * @param {Array<Light>} materialLights - The material lights.
  443. * @return {Array<Object>} The lights data for the given material lights.
  444. */
  445. getLightsData( materialLights, lights ) {
  446. lights.length = 0;
  447. for ( const light of materialLights ) {
  448. if ( light.isSpotLight === true && light.map !== null ) {
  449. // only add lights that have a map
  450. lights.push( { map: light.map.version } );
  451. }
  452. }
  453. return lights;
  454. }
  455. /**
  456. * Returns the lights for the given lights node and render ID.
  457. *
  458. * @param {LightsNode} lightsNode - The lights node.
  459. * @param {number} renderId - The render ID.
  460. * @return {Array<Object>} The lights for the given lights node and render ID.
  461. */
  462. getLights( lightsNode, renderId ) {
  463. let cached = _lightsCache.get( lightsNode );
  464. if ( cached === undefined ) {
  465. cached = { renderId: -1, lightsData: [] };
  466. _lightsCache.set( lightsNode, cached );
  467. }
  468. if ( cached.renderId === renderId ) {
  469. return cached.lightsData;
  470. }
  471. cached.renderId = renderId;
  472. this.getLightsData( lightsNode.getBuiltinLights(), cached.lightsData );
  473. return cached.lightsData;
  474. }
  475. /**
  476. * Checks if the given render object requires a refresh.
  477. *
  478. * @param {RenderObject} renderObject - The render object.
  479. * @param {NodeFrame} nodeFrame - The current node frame.
  480. * @return {boolean} Whether the given render object requires a refresh or not.
  481. */
  482. needsRefresh( renderObject, nodeFrame ) {
  483. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) || this.needsVelocity( nodeFrame.renderer ) )
  484. return true;
  485. const { renderId } = nodeFrame;
  486. if ( this.renderId !== renderId ) {
  487. this.renderId = renderId;
  488. return true;
  489. }
  490. const isStatic = renderObject.object.static === true;
  491. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  492. if ( isStatic || isBundle )
  493. return false;
  494. const lightsData = this.getLights( renderObject.lightsNode, renderId );
  495. const notEqual = this.equals( renderObject, lightsData, renderId ) !== true;
  496. return notEqual;
  497. }
  498. }
  499. // Pre-compiled RegExp patterns for ignored files
  500. const IGNORED_FILES = [
  501. /^StackTrace\.js$/,
  502. /^TSLCore\.js$/,
  503. /^.*Node\.js$/,
  504. /^three\.webgpu.*\.js$/
  505. ];
  506. /**
  507. * Parses the stack trace and filters out ignored files.
  508. * Returns an array with function name, file, line, and column.
  509. */
  510. function getFilteredStack( stack ) {
  511. // Pattern to extract function name, file, line, and column from different browsers
  512. // Chrome: "at functionName (file.js:1:2)" or "at file.js:1:2"
  513. // Firefox: "functionName@file.js:1:2"
  514. const regex = /(?:at\s+(.+?)\s+\()?(?:(.+?)@)?([^@\s()]+):(\d+):(\d+)/;
  515. return stack.split( '\n' )
  516. .map( line => {
  517. const match = line.match( regex );
  518. if ( ! match ) return null; // Skip if line format is invalid
  519. // Chrome: match[1], Firefox: match[2]
  520. const fn = match[ 1 ] || match[ 2 ] || '';
  521. const file = match[ 3 ].split( '?' )[ 0 ]; // Clean file name (Vite/HMR)
  522. const lineNum = parseInt( match[ 4 ], 10 );
  523. const column = parseInt( match[ 5 ], 10 );
  524. // Extract only the filename from full path
  525. const fileName = file.split( '/' ).pop();
  526. return {
  527. fn: fn,
  528. file: fileName,
  529. line: lineNum,
  530. column: column
  531. };
  532. } )
  533. .filter( frame => {
  534. // Only keep frames that are valid and not in the ignore list
  535. return frame && ! IGNORED_FILES.some( regex => regex.test( frame.file ) );
  536. } );
  537. }
  538. /**
  539. * Class representing a stack trace for debugging purposes.
  540. */
  541. class StackTrace {
  542. /**
  543. * Creates a StackTrace instance by capturing and filtering the current stack trace.
  544. *
  545. * @param {Error|string|null} stackMessage - An optional stack trace to use instead of capturing a new one.
  546. */
  547. constructor( stackMessage = null ) {
  548. /**
  549. * This flag can be used for type testing.
  550. *
  551. * @type {boolean}
  552. * @readonly
  553. * @default true
  554. */
  555. this.isStackTrace = true;
  556. /**
  557. * The stack trace.
  558. *
  559. * @type {Array<{fn: string, file: string, line: number, column: number}>}
  560. */
  561. this.stack = getFilteredStack( stackMessage ? stackMessage : new Error().stack );
  562. }
  563. /**
  564. * Returns a formatted location string of the top stack frame.
  565. *
  566. * @returns {string} The formatted stack trace message.
  567. */
  568. getLocation() {
  569. if ( this.stack.length === 0 ) {
  570. return '[Unknown location]';
  571. }
  572. const mainStack = this.stack[ 0 ];
  573. const fn = mainStack.fn;
  574. const fnName = fn ? `"${ fn }()" at ` : '';
  575. return `${fnName}"${mainStack.file}:${mainStack.line}"`; // :${mainStack.column}
  576. }
  577. /**
  578. * Returns the full error message including the stack trace.
  579. *
  580. * @param {string} message - The error message.
  581. * @returns {string} The full error message with stack trace.
  582. */
  583. getError( message ) {
  584. if ( this.stack.length === 0 ) {
  585. return message;
  586. }
  587. // Output: "Error: message\n at functionName (file.js:line:column)"
  588. const stackString = this.stack.map( frame => {
  589. const location = `${ frame.file }:${ frame.line }:${ frame.column }`;
  590. if ( frame.fn ) {
  591. return ` at ${ frame.fn } (${ location })`;
  592. }
  593. return ` at ${ location }`;
  594. } ).join( '\n' );
  595. return `${ message }\n${ stackString }`;
  596. }
  597. }
  598. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  599. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  600. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  601. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  602. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  603. function cyrb53( value, seed = 0 ) {
  604. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  605. if ( Array.isArray( value ) ) {
  606. for ( let i = 0, val; i < value.length; i ++ ) {
  607. val = value[ i ];
  608. h1 = Math.imul( h1 ^ val, 2654435761 );
  609. h2 = Math.imul( h2 ^ val, 1597334677 );
  610. }
  611. } else {
  612. for ( let i = 0, ch; i < value.length; i ++ ) {
  613. ch = value.charCodeAt( i );
  614. h1 = Math.imul( h1 ^ ch, 2654435761 );
  615. h2 = Math.imul( h2 ^ ch, 1597334677 );
  616. }
  617. }
  618. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  619. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  620. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  621. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  622. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  623. }
  624. /**
  625. * Computes a hash for the given string.
  626. *
  627. * @private
  628. * @method
  629. * @param {string} str - The string to be hashed.
  630. * @return {number} The hash.
  631. */
  632. const hashString = ( str ) => cyrb53( str );
  633. /**
  634. * Computes a hash for the given array.
  635. *
  636. * @private
  637. * @method
  638. * @param {Array<number>} array - The array to be hashed.
  639. * @return {number} The hash.
  640. */
  641. const hashArray = ( array ) => cyrb53( array );
  642. /**
  643. * Computes a hash for the given list of parameters.
  644. *
  645. * @private
  646. * @method
  647. * @param {...number} params - A list of parameters.
  648. * @return {number} The hash.
  649. */
  650. const hash$1 = ( ...params ) => cyrb53( params );
  651. const typeFromLength = /*@__PURE__*/ new Map( [
  652. [ 1, 'float' ],
  653. [ 2, 'vec2' ],
  654. [ 3, 'vec3' ],
  655. [ 4, 'vec4' ],
  656. [ 9, 'mat3' ],
  657. [ 16, 'mat4' ]
  658. ] );
  659. const dataFromObject = /*@__PURE__*/ new WeakMap();
  660. /**
  661. * Returns the data type for the given the length.
  662. *
  663. * @private
  664. * @method
  665. * @param {number} length - The length.
  666. * @return {string} The data type.
  667. */
  668. function getTypeFromLength( length ) {
  669. return typeFromLength.get( length );
  670. }
  671. /**
  672. * Returns the typed array for the given data type.
  673. *
  674. * @private
  675. * @method
  676. * @param {string} type - The data type.
  677. * @return {TypedArray} The typed array.
  678. */
  679. function getTypedArrayFromType( type ) {
  680. // Handle component type for vectors and matrices
  681. if ( /[iu]?vec\d/.test( type ) ) {
  682. // Handle int vectors
  683. if ( type.startsWith( 'ivec' ) ) return Int32Array;
  684. // Handle uint vectors
  685. if ( type.startsWith( 'uvec' ) ) return Uint32Array;
  686. // Default to float vectors
  687. return Float32Array;
  688. }
  689. // Handle matrices (always float)
  690. if ( /mat\d/.test( type ) ) return Float32Array;
  691. // Basic types
  692. if ( /float/.test( type ) ) return Float32Array;
  693. if ( /uint/.test( type ) ) return Uint32Array;
  694. if ( /int/.test( type ) ) return Int32Array;
  695. throw new Error( `THREE.NodeUtils: Unsupported type: ${type}` );
  696. }
  697. /**
  698. * Returns the length for the given data type.
  699. *
  700. * @private
  701. * @method
  702. * @param {string} type - The data type.
  703. * @return {number} The length.
  704. */
  705. function getLengthFromType( type ) {
  706. if ( /float|int|uint|bool/.test( type ) ) return 1;
  707. if ( /vec2/.test( type ) ) return 2;
  708. if ( /vec3/.test( type ) ) return 3;
  709. if ( /vec4/.test( type ) ) return 4;
  710. if ( /mat2/.test( type ) ) return 4;
  711. if ( /mat3/.test( type ) ) return 9;
  712. if ( /mat4/.test( type ) ) return 16;
  713. error( `TSL: Unsupported type: ${ type }`, new StackTrace() );
  714. }
  715. /**
  716. * Returns the gpu memory length for the given data type in 4-byte elements.
  717. *
  718. * @private
  719. * @method
  720. * @param {string} type - The data type.
  721. * @return {number} The memory length in 4-byte elements.
  722. */
  723. function getMemoryLengthFromType( type ) {
  724. if ( /float|int|uint|bool/.test( type ) ) return 1;
  725. if ( /vec2/.test( type ) ) return 2;
  726. if ( /vec3/.test( type ) ) return 3;
  727. if ( /vec4/.test( type ) ) return 4;
  728. if ( /mat2/.test( type ) ) return 4;
  729. if ( /mat3/.test( type ) ) return 12;
  730. if ( /mat4/.test( type ) ) return 16;
  731. error( `TSL: Unsupported type: ${ type }`, new StackTrace() );
  732. }
  733. /**
  734. * Returns the alignment requirement for the given data type in 4-byte elements.
  735. *
  736. * @private
  737. * @method
  738. * @param {string} type - The data type.
  739. * @return {number} The alignment requirement in 4-byte elements.
  740. */
  741. function getAlignmentFromType( type ) {
  742. if ( /float|int|uint|bool/.test( type ) ) return 1;
  743. if ( /vec2/.test( type ) ) return 2;
  744. if ( /vec3/.test( type ) ) return 4;
  745. if ( /vec4/.test( type ) ) return 4;
  746. if ( /mat2/.test( type ) ) return 2;
  747. if ( /mat3/.test( type ) ) return 4;
  748. if ( /mat4/.test( type ) ) return 4;
  749. error( `TSL: Unsupported type: ${ type }`, new StackTrace() );
  750. }
  751. /**
  752. * Returns the data type for the given value.
  753. *
  754. * @private
  755. * @method
  756. * @param {any} value - The value.
  757. * @return {?string} The data type.
  758. */
  759. function getValueType( value ) {
  760. if ( value === undefined || value === null ) return null;
  761. const typeOf = typeof value;
  762. if ( value.isNode === true ) {
  763. return 'node';
  764. } else if ( typeOf === 'number' ) {
  765. return 'float';
  766. } else if ( typeOf === 'boolean' ) {
  767. return 'bool';
  768. } else if ( typeOf === 'string' ) {
  769. return 'string';
  770. } else if ( typeOf === 'function' ) {
  771. return 'shader';
  772. } else if ( value.isVector2 === true ) {
  773. return 'vec2';
  774. } else if ( value.isVector3 === true ) {
  775. return 'vec3';
  776. } else if ( value.isVector4 === true ) {
  777. return 'vec4';
  778. } else if ( value.isMatrix2 === true ) {
  779. return 'mat2';
  780. } else if ( value.isMatrix3 === true ) {
  781. return 'mat3';
  782. } else if ( value.isMatrix4 === true ) {
  783. return 'mat4';
  784. } else if ( value.isColor === true ) {
  785. return 'color';
  786. } else if ( value instanceof ArrayBuffer ) {
  787. return 'ArrayBuffer';
  788. }
  789. return null;
  790. }
  791. /**
  792. * Returns the node data type for the given texture.
  793. *
  794. * @private
  795. * @method
  796. * @param {Texture} texture - The texture.
  797. * @return {string} The data type.
  798. */
  799. function getTextureType( texture ) {
  800. if ( texture.isDepthTexture === true ) {
  801. return 'float';
  802. }
  803. const format = texture.format;
  804. let length;
  805. if ( format === RedFormat || format === RedIntegerFormat || format === DepthFormat || format === DepthStencilFormat || format === AlphaFormat ) {
  806. length = 1;
  807. } else if ( format === RGFormat || format === RGIntegerFormat ) {
  808. length = 2;
  809. } else if ( format === RGBFormat || format === RGBIntegerFormat ) {
  810. length = 3;
  811. } else {
  812. length = 4;
  813. }
  814. let componentType;
  815. if ( texture.type === UnsignedIntType ) {
  816. componentType = 'uint';
  817. } else if ( texture.type === IntType ) {
  818. componentType = 'int';
  819. } else {
  820. componentType = 'float';
  821. }
  822. if ( length === 1 ) return componentType;
  823. let baseType = getTypeFromLength( length );
  824. if ( componentType !== 'float' ) {
  825. baseType = componentType[ 0 ] + baseType;
  826. }
  827. return baseType;
  828. }
  829. /**
  830. * Returns the value/object for the given data type and parameters.
  831. *
  832. * @private
  833. * @method
  834. * @param {string} type - The given type.
  835. * @param {...any} params - A parameter list.
  836. * @return {any} The value/object.
  837. */
  838. function getValueFromType( type, ...params ) {
  839. const last4 = type ? type.slice( -4 ) : undefined;
  840. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  841. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  842. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  843. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  844. }
  845. if ( type === 'color' ) {
  846. return new Color( ...params );
  847. } else if ( last4 === 'vec2' ) {
  848. return new Vector2( ...params );
  849. } else if ( last4 === 'vec3' ) {
  850. return new Vector3( ...params );
  851. } else if ( last4 === 'vec4' ) {
  852. return new Vector4( ...params );
  853. } else if ( last4 === 'mat2' ) {
  854. return new Matrix2( ...params );
  855. } else if ( last4 === 'mat3' ) {
  856. return new Matrix3( ...params );
  857. } else if ( last4 === 'mat4' ) {
  858. return new Matrix4( ...params );
  859. } else if ( type === 'bool' ) {
  860. return params[ 0 ] || false;
  861. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  862. return params[ 0 ] || 0;
  863. } else if ( type === 'string' ) {
  864. return params[ 0 ] || '';
  865. } else if ( type === 'ArrayBuffer' ) {
  866. return base64ToArrayBuffer( params[ 0 ] );
  867. }
  868. return null;
  869. }
  870. /**
  871. * Gets the object data that can be shared between different rendering steps.
  872. *
  873. * @private
  874. * @param {Object} object - The object to get the data for.
  875. * @return {Object} The object data.
  876. */
  877. function getDataFromObject( object ) {
  878. let data = dataFromObject.get( object );
  879. if ( data === undefined ) {
  880. data = {};
  881. dataFromObject.set( object, data );
  882. }
  883. return data;
  884. }
  885. /**
  886. * Converts the given array buffer to a Base64 string.
  887. *
  888. * @private
  889. * @method
  890. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  891. * @return {string} The Base64 string.
  892. */
  893. function arrayBufferToBase64( arrayBuffer ) {
  894. let chars = '';
  895. const array = new Uint8Array( arrayBuffer );
  896. for ( let i = 0; i < array.length; i ++ ) {
  897. chars += String.fromCharCode( array[ i ] );
  898. }
  899. return btoa( chars );
  900. }
  901. /**
  902. * Converts the given Base64 string to an array buffer.
  903. *
  904. * @private
  905. * @method
  906. * @param {string} base64 - The Base64 string.
  907. * @return {ArrayBuffer} The array buffer.
  908. */
  909. function base64ToArrayBuffer( base64 ) {
  910. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  911. }
  912. var NodeUtils = /*#__PURE__*/Object.freeze({
  913. __proto__: null,
  914. arrayBufferToBase64: arrayBufferToBase64,
  915. base64ToArrayBuffer: base64ToArrayBuffer,
  916. getAlignmentFromType: getAlignmentFromType,
  917. getDataFromObject: getDataFromObject,
  918. getLengthFromType: getLengthFromType,
  919. getMemoryLengthFromType: getMemoryLengthFromType,
  920. getTextureType: getTextureType,
  921. getTypeFromLength: getTypeFromLength,
  922. getTypedArrayFromType: getTypedArrayFromType,
  923. getValueFromType: getValueFromType,
  924. getValueType: getValueType,
  925. hash: hash$1,
  926. hashArray: hashArray,
  927. hashString: hashString
  928. });
  929. /**
  930. * Possible shader stages.
  931. *
  932. * @property {string} VERTEX The vertex shader stage.
  933. * @property {string} FRAGMENT The fragment shader stage.
  934. */
  935. const NodeShaderStage = {
  936. VERTEX: 'vertex',
  937. FRAGMENT: 'fragment'
  938. };
  939. /**
  940. * Update types of a node.
  941. *
  942. * @property {string} NONE The update method is not executed.
  943. * @property {string} FRAME The update method is executed per frame.
  944. * @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.
  945. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  946. */
  947. const NodeUpdateType = {
  948. NONE: 'none',
  949. FRAME: 'frame',
  950. RENDER: 'render',
  951. OBJECT: 'object'
  952. };
  953. /**
  954. * Data types of a node.
  955. *
  956. * @property {string} BOOLEAN Boolean type.
  957. * @property {string} INTEGER Integer type.
  958. * @property {string} FLOAT Float type.
  959. * @property {string} VECTOR2 Two-dimensional vector type.
  960. * @property {string} VECTOR3 Three-dimensional vector type.
  961. * @property {string} VECTOR4 Four-dimensional vector type.
  962. * @property {string} MATRIX2 2x2 matrix type.
  963. * @property {string} MATRIX3 3x3 matrix type.
  964. * @property {string} MATRIX4 4x4 matrix type.
  965. */
  966. const NodeType = {
  967. BOOLEAN: 'bool',
  968. INTEGER: 'int',
  969. FLOAT: 'float',
  970. VECTOR2: 'vec2',
  971. VECTOR3: 'vec3',
  972. VECTOR4: 'vec4',
  973. MATRIX2: 'mat2',
  974. MATRIX3: 'mat3',
  975. MATRIX4: 'mat4'
  976. };
  977. /**
  978. * Access types of a node. These are relevant for compute and storage usage.
  979. *
  980. * @property {string} READ_ONLY Read-only access
  981. * @property {string} WRITE_ONLY Write-only access.
  982. * @property {string} READ_WRITE Read and write access.
  983. */
  984. const NodeAccess = {
  985. READ_ONLY: 'readOnly',
  986. WRITE_ONLY: 'writeOnly',
  987. READ_WRITE: 'readWrite',
  988. };
  989. const defaultShaderStages = [ 'fragment', 'vertex' ];
  990. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  991. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  992. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  993. const _parentBuildStage = {
  994. analyze: 'setup',
  995. generate: 'analyze'
  996. };
  997. let _nodeId = 0;
  998. /**
  999. * Base class for all nodes.
  1000. *
  1001. * @augments EventDispatcher
  1002. */
  1003. class Node extends EventDispatcher {
  1004. static get type() {
  1005. return 'Node';
  1006. }
  1007. /**
  1008. * Constructs a new node.
  1009. *
  1010. * @param {?string} nodeType - The node type.
  1011. */
  1012. constructor( nodeType = null ) {
  1013. super();
  1014. /**
  1015. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  1016. *
  1017. * @type {?string}
  1018. * @default null
  1019. */
  1020. this.nodeType = nodeType;
  1021. /**
  1022. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  1023. *
  1024. * @type {string}
  1025. * @default 'none'
  1026. */
  1027. this.updateType = NodeUpdateType.NONE;
  1028. /**
  1029. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  1030. *
  1031. * @type {string}
  1032. * @default 'none'
  1033. */
  1034. this.updateBeforeType = NodeUpdateType.NONE;
  1035. /**
  1036. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  1037. *
  1038. * @type {string}
  1039. * @default 'none'
  1040. */
  1041. this.updateAfterType = NodeUpdateType.NONE;
  1042. /**
  1043. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  1044. *
  1045. * @type {number}
  1046. * @readonly
  1047. * @default 0
  1048. */
  1049. this.version = 0;
  1050. /**
  1051. * The name of the node.
  1052. *
  1053. * @type {string}
  1054. * @default ''
  1055. */
  1056. this.name = '';
  1057. /**
  1058. * Whether this node is global or not. This property is relevant for the internal
  1059. * node caching system. All nodes which should be declared just once should
  1060. * set this flag to `true` (a typical example is {@link AttributeNode}).
  1061. *
  1062. * @type {boolean}
  1063. * @default false
  1064. */
  1065. this.global = false;
  1066. /**
  1067. * Create a list of parents for this node during the build process.
  1068. *
  1069. * @type {boolean}
  1070. * @default false
  1071. */
  1072. this.parents = false;
  1073. /**
  1074. * This flag can be used for type testing.
  1075. *
  1076. * @type {boolean}
  1077. * @readonly
  1078. * @default true
  1079. */
  1080. this.isNode = true;
  1081. // private
  1082. this._beforeNodes = null;
  1083. /**
  1084. * The cache key of this node.
  1085. *
  1086. * @private
  1087. * @type {?number}
  1088. * @default null
  1089. */
  1090. this._cacheKey = null;
  1091. /**
  1092. * The UUID of the node.
  1093. *
  1094. * @type {string}
  1095. * @default null
  1096. * @private
  1097. */
  1098. this._uuid = null;
  1099. /**
  1100. * The cache key's version.
  1101. *
  1102. * @private
  1103. * @type {number}
  1104. * @default 0
  1105. */
  1106. this._cacheKeyVersion = 0;
  1107. /**
  1108. * The unique ID of the node.
  1109. *
  1110. * @type {number}
  1111. * @readonly
  1112. */
  1113. this.id = _nodeId ++;
  1114. /**
  1115. * The stack trace of the node for debugging purposes.
  1116. *
  1117. * @type {?string}
  1118. * @default null
  1119. */
  1120. this.stackTrace = null;
  1121. if ( Node.captureStackTrace === true ) {
  1122. this.stackTrace = new StackTrace();
  1123. }
  1124. }
  1125. /**
  1126. * Set this property to `true` when the node should be regenerated.
  1127. *
  1128. * @type {boolean}
  1129. * @default false
  1130. * @param {boolean} value
  1131. */
  1132. set needsUpdate( value ) {
  1133. if ( value === true ) {
  1134. this.version ++;
  1135. }
  1136. }
  1137. /**
  1138. * The UUID of the node.
  1139. *
  1140. * @type {string}
  1141. * @readonly
  1142. */
  1143. get uuid() {
  1144. if ( this._uuid === null ) {
  1145. this._uuid = MathUtils.generateUUID();
  1146. }
  1147. return this._uuid;
  1148. }
  1149. /**
  1150. * The type of the class. The value is usually the constructor name.
  1151. *
  1152. * @type {string}
  1153. * @readonly
  1154. */
  1155. get type() {
  1156. return this.constructor.type;
  1157. }
  1158. /**
  1159. * Convenient method for defining {@link Node#update}.
  1160. *
  1161. * @param {Function} callback - The update method.
  1162. * @param {string} updateType - The update type.
  1163. * @return {Node} A reference to this node.
  1164. */
  1165. onUpdate( callback, updateType ) {
  1166. this.updateType = updateType;
  1167. this.update = callback.bind( this );
  1168. return this;
  1169. }
  1170. /**
  1171. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  1172. * this method automatically sets the update type to `FRAME`.
  1173. *
  1174. * @param {Function} callback - The update method.
  1175. * @return {Node} A reference to this node.
  1176. */
  1177. onFrameUpdate( callback ) {
  1178. return this.onUpdate( callback, NodeUpdateType.FRAME );
  1179. }
  1180. /**
  1181. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  1182. * this method automatically sets the update type to `RENDER`.
  1183. *
  1184. * @param {Function} callback - The update method.
  1185. * @return {Node} A reference to this node.
  1186. */
  1187. onRenderUpdate( callback ) {
  1188. return this.onUpdate( callback, NodeUpdateType.RENDER );
  1189. }
  1190. /**
  1191. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  1192. * this method automatically sets the update type to `OBJECT`.
  1193. *
  1194. * @param {Function} callback - The update method.
  1195. * @return {Node} A reference to this node.
  1196. */
  1197. onObjectUpdate( callback ) {
  1198. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  1199. }
  1200. /**
  1201. * Convenient method for defining {@link Node#updateReference}.
  1202. *
  1203. * @param {Function} callback - The update method.
  1204. * @return {Node} A reference to this node.
  1205. */
  1206. onReference( callback ) {
  1207. this.updateReference = callback.bind( this );
  1208. return this;
  1209. }
  1210. /**
  1211. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  1212. * to such objects based on a given state (e.g. the current node frame or builder).
  1213. *
  1214. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  1215. * @return {any} The updated reference.
  1216. */
  1217. updateReference( /*state*/ ) {
  1218. return this;
  1219. }
  1220. /**
  1221. * By default this method returns the value of the {@link Node#global} flag. This method
  1222. * can be overwritten in derived classes if an analytical way is required to determine the
  1223. * global cache referring to the current shader-stage.
  1224. *
  1225. * @param {NodeBuilder} builder - The current node builder.
  1226. * @return {boolean} Whether this node is global or not.
  1227. */
  1228. isGlobal( /*builder*/ ) {
  1229. return this.global;
  1230. }
  1231. /**
  1232. * Generator function that can be used to iterate over the child nodes.
  1233. *
  1234. * @generator
  1235. * @yields {Node} A child node.
  1236. */
  1237. * getChildren() {
  1238. for ( const { childNode } of this._getChildren() ) {
  1239. yield childNode;
  1240. }
  1241. }
  1242. /**
  1243. * Calling this method dispatches the `dispose` event. This event can be used
  1244. * to register event listeners for clean up tasks.
  1245. */
  1246. dispose() {
  1247. this.dispatchEvent( { type: 'dispose' } );
  1248. }
  1249. /**
  1250. * Callback for {@link Node#traverse}.
  1251. *
  1252. * @callback traverseCallback
  1253. * @param {Node} node - The current node.
  1254. */
  1255. /**
  1256. * Can be used to traverse through the node's hierarchy.
  1257. *
  1258. * @param {traverseCallback} callback - A callback that is executed per node.
  1259. */
  1260. traverse( callback ) {
  1261. callback( this );
  1262. for ( const childNode of this.getChildren() ) {
  1263. childNode.traverse( callback );
  1264. }
  1265. }
  1266. /**
  1267. * Returns the child nodes of this node.
  1268. *
  1269. * @private
  1270. * @param {Set<Node>} [ignores=new Set()] - A set of nodes to ignore during the search to avoid circular references.
  1271. * @returns {Array<Object>} An array of objects describing the child nodes.
  1272. */
  1273. _getChildren( ignores = new Set() ) {
  1274. const children = [];
  1275. // avoid circular references
  1276. ignores.add( this );
  1277. for ( const property of Object.getOwnPropertyNames( this ) ) {
  1278. const object = this[ property ];
  1279. // Ignore private properties and ignored nodes.
  1280. if ( property.startsWith( '_' ) === true || ignores.has( object ) ) continue;
  1281. if ( Array.isArray( object ) === true ) {
  1282. for ( let i = 0; i < object.length; i ++ ) {
  1283. const child = object[ i ];
  1284. if ( child && child.isNode === true ) {
  1285. children.push( { property, index: i, childNode: child } );
  1286. }
  1287. }
  1288. } else if ( object && object.isNode === true ) {
  1289. children.push( { property, childNode: object } );
  1290. } else if ( object && Object.getPrototypeOf( object ) === Object.prototype ) {
  1291. for ( const subProperty in object ) {
  1292. // Ignore private sub-properties.
  1293. if ( subProperty.startsWith( '_' ) === true ) continue;
  1294. const child = object[ subProperty ];
  1295. if ( child && child.isNode === true ) {
  1296. children.push( { property, index: subProperty, childNode: child } );
  1297. }
  1298. }
  1299. }
  1300. }
  1301. //
  1302. return children;
  1303. }
  1304. /**
  1305. * Returns the cache key for this node.
  1306. *
  1307. * @param {boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  1308. * @param {Set<Node>} [ignores=null] - A set of nodes to ignore during the computation of the cache key.
  1309. * @return {number} The cache key of the node.
  1310. */
  1311. getCacheKey( force = false, ignores = null ) {
  1312. force = force || this.version !== this._cacheKeyVersion;
  1313. if ( force === true || this._cacheKey === null ) {
  1314. if ( ignores === null ) ignores = new Set();
  1315. //
  1316. const values = [];
  1317. for ( const { property, childNode } of this._getChildren( ignores ) ) {
  1318. values.push( hashString( property.slice( 0, -4 ) ), childNode.getCacheKey( force, ignores ) );
  1319. }
  1320. //
  1321. this._cacheKey = hash$1( hashArray( values ), this.customCacheKey() );
  1322. this._cacheKeyVersion = this.version;
  1323. }
  1324. return this._cacheKey;
  1325. }
  1326. /**
  1327. * Generate a custom cache key for this node.
  1328. *
  1329. * @return {number} The cache key of the node.
  1330. */
  1331. customCacheKey() {
  1332. return this.id;
  1333. }
  1334. /**
  1335. * Returns the references to this node which is by default `this`.
  1336. *
  1337. * @return {Node} A reference to this node.
  1338. */
  1339. getScope() {
  1340. return this;
  1341. }
  1342. /**
  1343. * Returns the hash of the node which is used to identify the node. By default it's
  1344. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  1345. * depending on their implementation.
  1346. *
  1347. * @param {NodeBuilder} builder - The current node builder.
  1348. * @return {string} The hash.
  1349. */
  1350. getHash( /*builder*/ ) {
  1351. return String( this.id );
  1352. }
  1353. /**
  1354. * Returns the update type of {@link Node#update}.
  1355. *
  1356. * @return {NodeUpdateType} The update type.
  1357. */
  1358. getUpdateType() {
  1359. return this.updateType;
  1360. }
  1361. /**
  1362. * Returns the update type of {@link Node#updateBefore}.
  1363. *
  1364. * @return {NodeUpdateType} The update type.
  1365. */
  1366. getUpdateBeforeType() {
  1367. return this.updateBeforeType;
  1368. }
  1369. /**
  1370. * Returns the update type of {@link Node#updateAfter}.
  1371. *
  1372. * @return {NodeUpdateType} The update type.
  1373. */
  1374. getUpdateAfterType() {
  1375. return this.updateAfterType;
  1376. }
  1377. /**
  1378. * Certain types are composed of multiple elements. For example a `vec3`
  1379. * is composed of three `float` values. This method returns the type of
  1380. * these elements.
  1381. *
  1382. * @param {NodeBuilder} builder - The current node builder.
  1383. * @return {string} The type of the node.
  1384. */
  1385. getElementType( builder ) {
  1386. const type = this.getNodeType( builder );
  1387. const elementType = builder.getElementType( type );
  1388. return elementType;
  1389. }
  1390. /**
  1391. * Returns the node member type for the given name.
  1392. *
  1393. * @param {NodeBuilder} builder - The current node builder.
  1394. * @param {string} name - The name of the member.
  1395. * @return {string} The type of the node.
  1396. */
  1397. getMemberType( /*builder, name*/ ) {
  1398. return 'void';
  1399. }
  1400. /**
  1401. * Returns the node's type.
  1402. *
  1403. * @param {NodeBuilder} builder - The current node builder.
  1404. * @param {string} [output=null] - The output of the node.
  1405. * @return {string} The type of the node.
  1406. */
  1407. getNodeType( builder, output = null ) {
  1408. const nodeData = builder.getDataFromNode( this );
  1409. let type;
  1410. if ( output !== null ) {
  1411. nodeData.typeFromOutput = nodeData.typeFromOutput || {};
  1412. type = nodeData.typeFromOutput[ output ];
  1413. if ( type === undefined ) {
  1414. type = this.generateNodeType( builder, output );
  1415. nodeData.typeFromOutput[ output ] = type;
  1416. }
  1417. } else {
  1418. type = nodeData.type;
  1419. if ( type === undefined ) {
  1420. type = this.generateNodeType( builder );
  1421. nodeData.type = type;
  1422. }
  1423. }
  1424. return type;
  1425. }
  1426. /**
  1427. * Returns the node's type.
  1428. *
  1429. * @param {NodeBuilder} builder - The current node builder.
  1430. * @param {string} [output=null] - The output of the node.
  1431. * @return {string} The type of the node.
  1432. */
  1433. generateNodeType( builder, output = null ) {
  1434. const nodeProperties = builder.getNodeProperties( this );
  1435. if ( nodeProperties.outputNode ) {
  1436. return nodeProperties.outputNode.getNodeType( builder, output );
  1437. }
  1438. return this.nodeType;
  1439. }
  1440. /**
  1441. * This method is used during the build process of a node and ensures
  1442. * equal nodes are not built multiple times but just once. For example if
  1443. * `attribute( 'uv' )` is used multiple times by the user, the build
  1444. * process makes sure to process just the first node. It also handles
  1445. * node overrides if an override context is set.
  1446. *
  1447. * @param {NodeBuilder} builder - The current node builder.
  1448. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  1449. */
  1450. getShared( builder ) {
  1451. const hash = this.getHash( builder );
  1452. const nodeFromHash = builder.getNodeFromHash( hash );
  1453. let sharedNode = null;
  1454. if ( nodeFromHash && nodeFromHash !== this ) {
  1455. sharedNode = nodeFromHash;
  1456. } else if ( builder.context.overrideNodes ) {
  1457. const callback = builder.context.overrideNodes.get( this );
  1458. if ( callback ) {
  1459. const nodeData = builder.getDataFromNode( this );
  1460. if ( nodeData.isOverwritten !== true ) {
  1461. nodeData.isOverwritten = true;
  1462. // cancel the override for use the same node inside the callback
  1463. sharedNode = callback( builder ).overrideNode( this, null );
  1464. nodeData.sharedNode = sharedNode;
  1465. } else {
  1466. // avoid recursive override calls
  1467. sharedNode = nodeData.sharedNode;
  1468. }
  1469. }
  1470. }
  1471. return sharedNode || this;
  1472. }
  1473. /**
  1474. * Returns the number of elements in the node array.
  1475. *
  1476. * @param {NodeBuilder} builder - The current node builder.
  1477. * @return {?number} The number of elements in the node array.
  1478. */
  1479. getArrayCount( /*builder*/ ) {
  1480. return null;
  1481. }
  1482. /**
  1483. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  1484. * This method is often overwritten in derived modules to prepare the node which is used as a node's output/result.
  1485. * If an output node is prepared, then it must be returned in the `return` statement of the derived module's setup function.
  1486. *
  1487. * @param {NodeBuilder} builder - The current node builder.
  1488. * @return {?Node} The output node.
  1489. */
  1490. setup( builder ) {
  1491. const nodeProperties = builder.getNodeProperties( this );
  1492. let index = 0;
  1493. for ( const childNode of this.getChildren() ) {
  1494. nodeProperties[ 'node' + index ++ ] = childNode;
  1495. }
  1496. // return a outputNode if exists or null
  1497. return nodeProperties.outputNode || null;
  1498. }
  1499. /**
  1500. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  1501. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  1502. *
  1503. * @param {NodeBuilder} builder - The current node builder.
  1504. * @param {?Node} output - The target output node.
  1505. */
  1506. analyze( builder, output = null ) {
  1507. const usageCount = builder.increaseUsage( this );
  1508. if ( this.parents === true ) {
  1509. const nodeData = builder.getDataFromNode( this, 'any' );
  1510. nodeData.stages = nodeData.stages || {};
  1511. nodeData.stages[ builder.shaderStage ] = nodeData.stages[ builder.shaderStage ] || [];
  1512. nodeData.stages[ builder.shaderStage ].push( output );
  1513. }
  1514. if ( usageCount === 1 ) {
  1515. // node flow children
  1516. const nodeProperties = builder.getNodeProperties( this );
  1517. for ( const childNode of Object.values( nodeProperties ) ) {
  1518. if ( childNode && childNode.isNode === true ) {
  1519. childNode.build( builder, this );
  1520. }
  1521. }
  1522. }
  1523. }
  1524. /**
  1525. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  1526. * This state builds the output node and returns the resulting shader string.
  1527. *
  1528. * @param {NodeBuilder} builder - The current node builder.
  1529. * @param {?string} [output] - Can be used to define the output type.
  1530. * @return {?string} The generated shader string.
  1531. */
  1532. generate( builder, output ) {
  1533. const { outputNode } = builder.getNodeProperties( this );
  1534. if ( outputNode && outputNode.isNode === true ) {
  1535. return outputNode.build( builder, output );
  1536. }
  1537. }
  1538. /**
  1539. * The method can be implemented to update the node's internal state before it is used to render an object.
  1540. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  1541. *
  1542. * @abstract
  1543. * @param {NodeFrame} frame - A reference to the current node frame.
  1544. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1545. */
  1546. updateBefore( /*frame*/ ) {
  1547. warn( 'Abstract function.' );
  1548. }
  1549. /**
  1550. * The method can be implemented to update the node's internal state after it was used to render an object.
  1551. * The {@link Node#updateAfterType} property defines how often the update is executed.
  1552. *
  1553. * @abstract
  1554. * @param {NodeFrame} frame - A reference to the current node frame.
  1555. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1556. */
  1557. updateAfter( /*frame*/ ) {
  1558. warn( 'Abstract function.' );
  1559. }
  1560. /**
  1561. * The method can be implemented to update the node's internal state when it is used to render an object.
  1562. * The {@link Node#updateType} property defines how often the update is executed.
  1563. *
  1564. * @abstract
  1565. * @param {NodeFrame} frame - A reference to the current node frame.
  1566. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1567. */
  1568. update( /*frame*/ ) {
  1569. warn( 'Abstract function.' );
  1570. }
  1571. before( node ) {
  1572. if ( this._beforeNodes === null ) this._beforeNodes = [];
  1573. this._beforeNodes.push( node );
  1574. return this;
  1575. }
  1576. /**
  1577. * This method performs the build of a node. The behavior and return value depend on the current build stage:
  1578. * - **setup**: Prepares the node and its children for the build process. This process can also create new nodes. Returns the node itself or a variant.
  1579. * - **analyze**: Analyzes the node hierarchy for optimizations in the code generation stage. Returns `null`.
  1580. * - **generate**: Generates the shader code for the node. Returns the generated shader string.
  1581. *
  1582. * @param {NodeBuilder} builder - The current node builder.
  1583. * @param {?(string|Node)} [output=null] - Can be used to define the output type.
  1584. * @return {?(Node|string)} The result of the build process, depending on the build stage.
  1585. */
  1586. build( builder, output = null ) {
  1587. const refNode = this.getShared( builder );
  1588. if ( this !== refNode ) {
  1589. return refNode.build( builder, output );
  1590. }
  1591. //
  1592. if ( this._beforeNodes !== null ) {
  1593. const currentBeforeNodes = this._beforeNodes;
  1594. this._beforeNodes = null;
  1595. for ( const beforeNode of currentBeforeNodes ) {
  1596. beforeNode.build( builder, output );
  1597. }
  1598. this._beforeNodes = currentBeforeNodes;
  1599. }
  1600. //
  1601. const nodeData = builder.getDataFromNode( this );
  1602. nodeData.buildStages = nodeData.buildStages || {};
  1603. nodeData.buildStages[ builder.buildStage ] = true;
  1604. const parentBuildStage = _parentBuildStage[ builder.buildStage ];
  1605. if ( parentBuildStage && nodeData.buildStages[ parentBuildStage ] !== true ) {
  1606. // force parent build stage (setup or analyze)
  1607. const previousBuildStage = builder.getBuildStage();
  1608. builder.setBuildStage( parentBuildStage );
  1609. this.build( builder );
  1610. builder.setBuildStage( previousBuildStage );
  1611. }
  1612. //
  1613. builder.addChain( this );
  1614. /* Build stages expected results:
  1615. - "setup" -> Node
  1616. - "analyze" -> null
  1617. - "generate" -> String
  1618. */
  1619. let result = null;
  1620. const buildStage = builder.getBuildStage();
  1621. if ( buildStage === 'setup' ) {
  1622. builder.addNode( this );
  1623. this.updateReference( builder );
  1624. const properties = builder.getNodeProperties( this );
  1625. if ( properties.initialized !== true ) {
  1626. //const stackNodesBeforeSetup = builder.stack.nodes.length;
  1627. properties.initialized = true;
  1628. properties.outputNode = this.setup( builder ) || properties.outputNode || null;
  1629. /*if ( isNodeOutput && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  1630. // !! no outputNode !!
  1631. //outputNode = builder.stack;
  1632. }*/
  1633. for ( const childNode of Object.values( properties ) ) {
  1634. if ( childNode && childNode.isNode === true ) {
  1635. if ( childNode.parents === true ) {
  1636. const childProperties = builder.getNodeProperties( childNode );
  1637. childProperties.parents = childProperties.parents || [];
  1638. childProperties.parents.push( this );
  1639. }
  1640. childNode.build( builder );
  1641. }
  1642. }
  1643. builder.addSequentialNode( this );
  1644. }
  1645. result = properties.outputNode;
  1646. } else if ( buildStage === 'analyze' ) {
  1647. this.analyze( builder, output );
  1648. } else if ( buildStage === 'generate' ) {
  1649. // If generate has just one argument, it means the output type is not required.
  1650. // This means that the node does not handle output conversions internally,
  1651. // so the value is stored in a cache and the builder handles the conversion
  1652. // for all requested output types.
  1653. const isGenerateOnce = this.generate.length < 2;
  1654. if ( isGenerateOnce ) {
  1655. const type = this.getNodeType( builder );
  1656. const nodeData = builder.getDataFromNode( this );
  1657. result = nodeData.snippet;
  1658. if ( result === undefined ) {
  1659. if ( nodeData.generated === undefined ) {
  1660. nodeData.generated = true;
  1661. result = this.generate( builder ) || '';
  1662. nodeData.snippet = result;
  1663. } else {
  1664. warn( 'Node: Recursion detected.', this );
  1665. result = '/* Recursion detected. */';
  1666. }
  1667. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1668. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1669. }
  1670. result = builder.format( result, type, output );
  1671. } else {
  1672. result = this.generate( builder, output ) || '';
  1673. }
  1674. if ( result === '' && output !== null && output !== 'void' && output !== 'OutputType' ) {
  1675. // if no snippet is generated, return a default value
  1676. error( `TSL: Invalid generated code, expected a "${ output }".` );
  1677. result = builder.generateConst( output );
  1678. }
  1679. }
  1680. builder.removeChain( this );
  1681. return result;
  1682. }
  1683. /**
  1684. * Returns the child nodes as a JSON object.
  1685. *
  1686. * @return {Generator<Object>} An iterable list of serialized child objects as JSON.
  1687. */
  1688. getSerializeChildren() {
  1689. return this._getChildren();
  1690. }
  1691. /**
  1692. * Serializes the node to JSON.
  1693. *
  1694. * @param {Object} json - The output JSON object.
  1695. */
  1696. serialize( json ) {
  1697. const nodeChildren = this.getSerializeChildren();
  1698. const inputNodes = {};
  1699. for ( const { property, index, childNode } of nodeChildren ) {
  1700. if ( index !== undefined ) {
  1701. if ( inputNodes[ property ] === undefined ) {
  1702. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1703. }
  1704. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1705. } else {
  1706. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1707. }
  1708. }
  1709. if ( Object.keys( inputNodes ).length > 0 ) {
  1710. json.inputNodes = inputNodes;
  1711. }
  1712. }
  1713. /**
  1714. * Deserializes the node from the given JSON.
  1715. *
  1716. * @param {Object} json - The JSON object.
  1717. */
  1718. deserialize( json ) {
  1719. if ( json.inputNodes !== undefined ) {
  1720. const nodes = json.meta.nodes;
  1721. for ( const property in json.inputNodes ) {
  1722. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1723. const inputArray = [];
  1724. for ( const uuid of json.inputNodes[ property ] ) {
  1725. inputArray.push( nodes[ uuid ] );
  1726. }
  1727. this[ property ] = inputArray;
  1728. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1729. const inputObject = {};
  1730. for ( const subProperty in json.inputNodes[ property ] ) {
  1731. const uuid = json.inputNodes[ property ][ subProperty ];
  1732. inputObject[ subProperty ] = nodes[ uuid ];
  1733. }
  1734. this[ property ] = inputObject;
  1735. } else {
  1736. const uuid = json.inputNodes[ property ];
  1737. this[ property ] = nodes[ uuid ];
  1738. }
  1739. }
  1740. }
  1741. }
  1742. /**
  1743. * Serializes the node into the three.js JSON Object/Scene format.
  1744. *
  1745. * @param {?Object} meta - An optional JSON object that already holds serialized data from other scene objects.
  1746. * @return {Object} The serialized node.
  1747. */
  1748. toJSON( meta ) {
  1749. const { uuid, type } = this;
  1750. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1751. if ( isRoot ) {
  1752. meta = {
  1753. textures: {},
  1754. images: {},
  1755. nodes: {}
  1756. };
  1757. }
  1758. // serialize
  1759. let data = meta.nodes[ uuid ];
  1760. if ( data === undefined ) {
  1761. data = {
  1762. uuid,
  1763. type,
  1764. meta,
  1765. metadata: {
  1766. version: 4.7,
  1767. type: 'Node',
  1768. generator: 'Node.toJSON'
  1769. }
  1770. };
  1771. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1772. this.serialize( data );
  1773. delete data.meta;
  1774. }
  1775. // TODO: Copied from Object3D.toJSON
  1776. function extractFromCache( cache ) {
  1777. const values = [];
  1778. for ( const key in cache ) {
  1779. const data = cache[ key ];
  1780. delete data.metadata;
  1781. values.push( data );
  1782. }
  1783. return values;
  1784. }
  1785. if ( isRoot ) {
  1786. const textures = extractFromCache( meta.textures );
  1787. const images = extractFromCache( meta.images );
  1788. const nodes = extractFromCache( meta.nodes );
  1789. if ( textures.length > 0 ) data.textures = textures;
  1790. if ( images.length > 0 ) data.images = images;
  1791. if ( nodes.length > 0 ) data.nodes = nodes;
  1792. }
  1793. return data;
  1794. }
  1795. }
  1796. /**
  1797. * Enables or disables the automatic capturing of stack traces for nodes.
  1798. *
  1799. * @type {boolean}
  1800. * @default false
  1801. */
  1802. Node.captureStackTrace = false;
  1803. /**
  1804. * Base class for representing element access on an array-like
  1805. * node data structures.
  1806. *
  1807. * @augments Node
  1808. */
  1809. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1810. static get type() {
  1811. return 'ArrayElementNode';
  1812. }
  1813. /**
  1814. * Constructs an array element node.
  1815. *
  1816. * @param {Node} node - The array-like node.
  1817. * @param {Node} indexNode - The index node that defines the element access.
  1818. */
  1819. constructor( node, indexNode ) {
  1820. super();
  1821. /**
  1822. * The array-like node.
  1823. *
  1824. * @type {Node}
  1825. */
  1826. this.node = node;
  1827. /**
  1828. * The index node that defines the element access.
  1829. *
  1830. * @type {Node}
  1831. */
  1832. this.indexNode = indexNode;
  1833. /**
  1834. * This flag can be used for type testing.
  1835. *
  1836. * @type {boolean}
  1837. * @readonly
  1838. * @default true
  1839. */
  1840. this.isArrayElementNode = true;
  1841. }
  1842. /**
  1843. * This method is overwritten since the node type is inferred from the array-like node.
  1844. *
  1845. * @param {NodeBuilder} builder - The current node builder.
  1846. * @return {string} The node type.
  1847. */
  1848. generateNodeType( builder ) {
  1849. return this.node.getElementType( builder );
  1850. }
  1851. /**
  1852. * This method is overwritten since the member type is inferred from the array-like node.
  1853. *
  1854. * @param {NodeBuilder} builder - The current node builder.
  1855. * @param {string} name - The member name.
  1856. * @return {string} The member type.
  1857. */
  1858. getMemberType( builder, name ) {
  1859. return this.node.getMemberType( builder, name );
  1860. }
  1861. generate( builder ) {
  1862. const indexType = this.indexNode.getNodeType( builder );
  1863. const nodeSnippet = this.node.build( builder );
  1864. const indexSnippet = this.indexNode.build( builder, ! builder.isVector( indexType ) && builder.isInteger( indexType ) ? indexType : 'uint' );
  1865. return `${ nodeSnippet }[ ${ indexSnippet } ]`;
  1866. }
  1867. }
  1868. /**
  1869. * This module is part of the TSL core and usually not used in app level code.
  1870. * It represents a convert operation during the shader generation process
  1871. * meaning it converts the data type of a node to a target data type.
  1872. *
  1873. * @augments Node
  1874. */
  1875. class ConvertNode extends Node {
  1876. static get type() {
  1877. return 'ConvertNode';
  1878. }
  1879. /**
  1880. * Constructs a new convert node.
  1881. *
  1882. * @param {Node} node - The node which type should be converted.
  1883. * @param {string} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1884. */
  1885. constructor( node, convertTo ) {
  1886. super();
  1887. /**
  1888. * The node which type should be converted.
  1889. *
  1890. * @type {Node}
  1891. */
  1892. this.node = node;
  1893. /**
  1894. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1895. *
  1896. * @type {string}
  1897. */
  1898. this.convertTo = convertTo;
  1899. }
  1900. /**
  1901. * This method is overwritten since the implementation tries to infer the best
  1902. * matching type from the {@link ConvertNode#convertTo} property.
  1903. *
  1904. * @param {NodeBuilder} builder - The current node builder.
  1905. * @return {string} The node type.
  1906. */
  1907. generateNodeType( builder ) {
  1908. const requestType = this.node.getNodeType( builder );
  1909. let convertTo = null;
  1910. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1911. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1912. convertTo = overloadingType;
  1913. }
  1914. }
  1915. return convertTo;
  1916. }
  1917. serialize( data ) {
  1918. super.serialize( data );
  1919. data.convertTo = this.convertTo;
  1920. }
  1921. deserialize( data ) {
  1922. super.deserialize( data );
  1923. this.convertTo = data.convertTo;
  1924. }
  1925. generate( builder, output ) {
  1926. const node = this.node;
  1927. const type = this.getNodeType( builder );
  1928. const snippet = node.build( builder, type );
  1929. return builder.format( snippet, type, output );
  1930. }
  1931. }
  1932. /**
  1933. * This module uses cache management to create temporary variables
  1934. * if the node is used more than once to prevent duplicate calculations.
  1935. *
  1936. * The class acts as a base class for many other nodes types.
  1937. *
  1938. * @augments Node
  1939. */
  1940. class TempNode extends Node {
  1941. static get type() {
  1942. return 'TempNode';
  1943. }
  1944. /**
  1945. * Constructs a temp node.
  1946. *
  1947. * @param {?string} nodeType - The node type.
  1948. */
  1949. constructor( nodeType = null ) {
  1950. super( nodeType );
  1951. /**
  1952. * This flag can be used for type testing.
  1953. *
  1954. * @type {boolean}
  1955. * @readonly
  1956. * @default true
  1957. */
  1958. this.isTempNode = true;
  1959. }
  1960. /**
  1961. * Whether this node is used more than once in context of other nodes.
  1962. *
  1963. * @param {NodeBuilder} builder - The node builder.
  1964. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes.
  1965. */
  1966. hasDependencies( builder ) {
  1967. return builder.getDataFromNode( this ).usageCount > 1;
  1968. }
  1969. build( builder, output ) {
  1970. const buildStage = builder.getBuildStage();
  1971. if ( buildStage === 'generate' ) {
  1972. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1973. const nodeData = builder.getDataFromNode( this );
  1974. if ( nodeData.propertyName !== undefined ) {
  1975. return builder.format( nodeData.propertyName, type, output );
  1976. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1977. const snippet = super.build( builder, type );
  1978. const nodeVar = builder.getVarFromNode( this, null, type );
  1979. const propertyName = builder.getPropertyName( nodeVar );
  1980. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  1981. nodeData.snippet = snippet;
  1982. nodeData.propertyName = propertyName;
  1983. return builder.format( nodeData.propertyName, type, output );
  1984. }
  1985. }
  1986. return super.build( builder, output );
  1987. }
  1988. }
  1989. /**
  1990. * This module is part of the TSL core and usually not used in app level code.
  1991. * It represents a join operation during the shader generation process.
  1992. * For example in can compose/join two single floats into a `vec2` type.
  1993. *
  1994. * @augments TempNode
  1995. */
  1996. class JoinNode extends TempNode {
  1997. static get type() {
  1998. return 'JoinNode';
  1999. }
  2000. /**
  2001. * Constructs a new join node.
  2002. *
  2003. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  2004. * @param {?string} [nodeType=null] - The node type.
  2005. */
  2006. constructor( nodes = [], nodeType = null ) {
  2007. super( nodeType );
  2008. /**
  2009. * An array of nodes that should be joined.
  2010. *
  2011. * @type {Array<Node>}
  2012. */
  2013. this.nodes = nodes;
  2014. }
  2015. /**
  2016. * This method is overwritten since the node type must be inferred from the
  2017. * joined data length if not explicitly defined.
  2018. *
  2019. * @param {NodeBuilder} builder - The current node builder.
  2020. * @return {string} The node type.
  2021. */
  2022. generateNodeType( builder ) {
  2023. if ( this.nodeType !== null ) {
  2024. return builder.getVectorType( this.nodeType );
  2025. }
  2026. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  2027. }
  2028. generate( builder, output ) {
  2029. const type = this.getNodeType( builder );
  2030. const maxLength = builder.getTypeLength( type );
  2031. const nodes = this.nodes;
  2032. const primitiveType = builder.getComponentType( type );
  2033. const snippetValues = [];
  2034. let length = 0;
  2035. for ( const input of nodes ) {
  2036. if ( length >= maxLength ) {
  2037. error( `TSL: Length of parameters exceeds maximum length of function '${ type }()' type.`, this.stackTrace );
  2038. break;
  2039. }
  2040. let inputType = input.getNodeType( builder );
  2041. let inputTypeLength = builder.getTypeLength( inputType );
  2042. let inputSnippet;
  2043. if ( length + inputTypeLength > maxLength ) {
  2044. error( `TSL: Length of '${ type }()' data exceeds maximum length of output type.`, this.stackTrace );
  2045. inputTypeLength = maxLength - length;
  2046. inputType = builder.getTypeFromLength( inputTypeLength );
  2047. }
  2048. length += inputTypeLength;
  2049. inputSnippet = input.build( builder, inputType );
  2050. const inputPrimitiveType = builder.getComponentType( inputType );
  2051. if ( inputPrimitiveType !== primitiveType ) {
  2052. const targetType = builder.getTypeFromLength( inputTypeLength, primitiveType );
  2053. inputSnippet = builder.format( inputSnippet, inputType, targetType );
  2054. }
  2055. snippetValues.push( inputSnippet );
  2056. }
  2057. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  2058. return builder.format( snippet, type, output );
  2059. }
  2060. }
  2061. const _stringVectorComponents = vectorComponents.join( '' );
  2062. /**
  2063. * This module is part of the TSL core and usually not used in app level code.
  2064. * `SplitNode` represents a property access operation which means it is
  2065. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  2066. * For example:
  2067. * ```js
  2068. * const redValue = color.r;
  2069. * ```
  2070. *
  2071. * @augments Node
  2072. */
  2073. class SplitNode extends Node {
  2074. static get type() {
  2075. return 'SplitNode';
  2076. }
  2077. /**
  2078. * Constructs a new split node.
  2079. *
  2080. * @param {Node} node - The node that should be accessed.
  2081. * @param {string} [components='x'] - The components that should be accessed.
  2082. */
  2083. constructor( node, components = 'x' ) {
  2084. super();
  2085. /**
  2086. * The node that should be accessed.
  2087. *
  2088. * @type {Node}
  2089. */
  2090. this.node = node;
  2091. /**
  2092. * The components that should be accessed.
  2093. *
  2094. * @type {string}
  2095. */
  2096. this.components = components;
  2097. /**
  2098. * This flag can be used for type testing.
  2099. *
  2100. * @type {boolean}
  2101. * @readonly
  2102. * @default true
  2103. */
  2104. this.isSplitNode = true;
  2105. }
  2106. /**
  2107. * Returns the vector length which is computed based on the requested components.
  2108. *
  2109. * @return {number} The vector length.
  2110. */
  2111. getVectorLength() {
  2112. let vectorLength = this.components.length;
  2113. for ( const c of this.components ) {
  2114. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  2115. }
  2116. return vectorLength;
  2117. }
  2118. /**
  2119. * Returns the component type of the node's type.
  2120. *
  2121. * @param {NodeBuilder} builder - The current node builder.
  2122. * @return {string} The component type.
  2123. */
  2124. getComponentType( builder ) {
  2125. return builder.getComponentType( this.node.getNodeType( builder ) );
  2126. }
  2127. /**
  2128. * This method is overwritten since the node type is inferred from requested components.
  2129. *
  2130. * @param {NodeBuilder} builder - The current node builder.
  2131. * @return {string} The node type.
  2132. */
  2133. generateNodeType( builder ) {
  2134. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  2135. }
  2136. /**
  2137. * Returns the scope of the node.
  2138. *
  2139. * @return {Node} The scope of the node.
  2140. */
  2141. getScope() {
  2142. return this.node.getScope();
  2143. }
  2144. generate( builder, output ) {
  2145. const node = this.node;
  2146. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  2147. let snippet = null;
  2148. if ( nodeTypeLength > 1 ) {
  2149. let type = null;
  2150. const componentsLength = this.getVectorLength();
  2151. if ( componentsLength >= nodeTypeLength ) {
  2152. // needed expand the input node
  2153. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  2154. }
  2155. const nodeSnippet = node.build( builder, type );
  2156. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  2157. // unnecessary swizzle
  2158. snippet = builder.format( nodeSnippet, type, output );
  2159. } else {
  2160. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  2161. }
  2162. } else {
  2163. // ignore .components if .node returns float/integer
  2164. snippet = node.build( builder, output );
  2165. }
  2166. return snippet;
  2167. }
  2168. serialize( data ) {
  2169. super.serialize( data );
  2170. data.components = this.components;
  2171. }
  2172. deserialize( data ) {
  2173. super.deserialize( data );
  2174. this.components = data.components;
  2175. }
  2176. }
  2177. /**
  2178. * This module is part of the TSL core and usually not used in app level code.
  2179. * `SetNode` represents a set operation which means it is used to implement any
  2180. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  2181. * For example:
  2182. * ```js
  2183. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  2184. * ```
  2185. *
  2186. * @augments TempNode
  2187. */
  2188. class SetNode extends TempNode {
  2189. static get type() {
  2190. return 'SetNode';
  2191. }
  2192. /**
  2193. * Constructs a new set node.
  2194. *
  2195. * @param {Node} sourceNode - The node that should be updated.
  2196. * @param {string} components - The components that should be updated.
  2197. * @param {Node} targetNode - The value node.
  2198. */
  2199. constructor( sourceNode, components, targetNode ) {
  2200. super();
  2201. /**
  2202. * The node that should be updated.
  2203. *
  2204. * @type {Node}
  2205. */
  2206. this.sourceNode = sourceNode;
  2207. /**
  2208. * The components that should be updated.
  2209. *
  2210. * @type {string}
  2211. */
  2212. this.components = components;
  2213. /**
  2214. * The value node.
  2215. *
  2216. * @type {Node}
  2217. */
  2218. this.targetNode = targetNode;
  2219. }
  2220. /**
  2221. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  2222. *
  2223. * @param {NodeBuilder} builder - The current node builder.
  2224. * @return {string} The node type.
  2225. */
  2226. generateNodeType( builder ) {
  2227. return this.sourceNode.getNodeType( builder );
  2228. }
  2229. generate( builder ) {
  2230. const { sourceNode, components, targetNode } = this;
  2231. const sourceType = this.getNodeType( builder );
  2232. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  2233. const targetType = builder.getTypeFromLength( components.length, componentType );
  2234. const targetSnippet = targetNode.build( builder, targetType );
  2235. const sourceSnippet = sourceNode.build( builder, sourceType );
  2236. const length = builder.getTypeLength( sourceType );
  2237. const snippetValues = [];
  2238. for ( let i = 0; i < length; i ++ ) {
  2239. const component = vectorComponents[ i ];
  2240. if ( component === components[ 0 ] ) {
  2241. snippetValues.push( targetSnippet );
  2242. i += components.length - 1;
  2243. } else {
  2244. snippetValues.push( sourceSnippet + '.' + component );
  2245. }
  2246. }
  2247. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  2248. }
  2249. }
  2250. /**
  2251. * This module is part of the TSL core and usually not used in app level code.
  2252. * It represents a flip operation during the shader generation process
  2253. * meaning it flips normalized values with the following formula:
  2254. * ```
  2255. * x = 1 - x;
  2256. * ```
  2257. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  2258. * `flipSTPQ()` method invocations on node objects. For example:
  2259. * ```js
  2260. * uvNode = uvNode.flipY();
  2261. * ```
  2262. *
  2263. * @augments TempNode
  2264. */
  2265. class FlipNode extends TempNode {
  2266. static get type() {
  2267. return 'FlipNode';
  2268. }
  2269. /**
  2270. * Constructs a new flip node.
  2271. *
  2272. * @param {Node} sourceNode - The node which component(s) should be flipped.
  2273. * @param {string} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  2274. */
  2275. constructor( sourceNode, components ) {
  2276. super();
  2277. /**
  2278. * The node which component(s) should be flipped.
  2279. *
  2280. * @type {Node}
  2281. */
  2282. this.sourceNode = sourceNode;
  2283. /**
  2284. * The components that should be flipped e.g. `'x'` or `'xy'`.
  2285. *
  2286. * @type {string}
  2287. */
  2288. this.components = components;
  2289. }
  2290. /**
  2291. * This method is overwritten since the node type is inferred from the source node.
  2292. *
  2293. * @param {NodeBuilder} builder - The current node builder.
  2294. * @return {string} The node type.
  2295. */
  2296. generateNodeType( builder ) {
  2297. return this.sourceNode.getNodeType( builder );
  2298. }
  2299. generate( builder ) {
  2300. const { components, sourceNode } = this;
  2301. const sourceType = this.getNodeType( builder );
  2302. const sourceSnippet = sourceNode.build( builder );
  2303. const sourceCache = builder.getVarFromNode( this );
  2304. const sourceProperty = builder.getPropertyName( sourceCache );
  2305. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  2306. const length = builder.getTypeLength( sourceType );
  2307. const snippetValues = [];
  2308. let componentIndex = 0;
  2309. for ( let i = 0; i < length; i ++ ) {
  2310. const component = vectorComponents[ i ];
  2311. if ( component === components[ componentIndex ] ) {
  2312. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  2313. componentIndex ++;
  2314. } else {
  2315. snippetValues.push( sourceProperty + '.' + component );
  2316. }
  2317. }
  2318. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  2319. }
  2320. }
  2321. /**
  2322. * Base class for representing data input nodes.
  2323. *
  2324. * @augments Node
  2325. */
  2326. class InputNode extends Node {
  2327. static get type() {
  2328. return 'InputNode';
  2329. }
  2330. /**
  2331. * Constructs a new input node.
  2332. *
  2333. * @param {any} value - The value of this node. This can be any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  2334. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2335. */
  2336. constructor( value, nodeType = null ) {
  2337. super( nodeType );
  2338. /**
  2339. * This flag can be used for type testing.
  2340. *
  2341. * @type {boolean}
  2342. * @readonly
  2343. * @default true
  2344. */
  2345. this.isInputNode = true;
  2346. /**
  2347. * The value of this node. This can be any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  2348. *
  2349. * @type {any}
  2350. */
  2351. this.value = value;
  2352. /**
  2353. * The precision of the value in the shader.
  2354. *
  2355. * @type {?('low'|'medium'|'high')}
  2356. * @default null
  2357. */
  2358. this.precision = null;
  2359. }
  2360. generateNodeType( /*builder*/ ) {
  2361. if ( this.nodeType === null ) {
  2362. return getValueType( this.value );
  2363. }
  2364. return this.nodeType;
  2365. }
  2366. /**
  2367. * Returns the input type of the node which is by default the node type. Derived modules
  2368. * might overwrite this method and use a fixed type or compute one analytically.
  2369. *
  2370. * A typical example for different input and node types are textures. The input type of a
  2371. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  2372. *
  2373. * @param {NodeBuilder} builder - The current node builder.
  2374. * @return {string} The input type.
  2375. */
  2376. getInputType( builder ) {
  2377. return this.getNodeType( builder );
  2378. }
  2379. /**
  2380. * Sets the precision to the given value. The method can be
  2381. * overwritten in derived classes if the final precision must be computed
  2382. * analytically.
  2383. *
  2384. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  2385. * @return {InputNode} A reference to this node.
  2386. */
  2387. setPrecision( precision ) {
  2388. this.precision = precision;
  2389. return this;
  2390. }
  2391. serialize( data ) {
  2392. super.serialize( data );
  2393. data.value = this.value;
  2394. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  2395. data.valueType = getValueType( this.value );
  2396. data.nodeType = this.nodeType;
  2397. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  2398. data.precision = this.precision;
  2399. }
  2400. deserialize( data ) {
  2401. super.deserialize( data );
  2402. this.nodeType = data.nodeType;
  2403. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  2404. this.precision = data.precision || null;
  2405. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  2406. }
  2407. generate( /*builder, output*/ ) {
  2408. warn( 'Abstract function.' );
  2409. }
  2410. }
  2411. const _regNum = /float|u?int/;
  2412. /**
  2413. * Class for representing a constant value in the shader.
  2414. *
  2415. * @augments InputNode
  2416. */
  2417. class ConstNode extends InputNode {
  2418. static get type() {
  2419. return 'ConstNode';
  2420. }
  2421. /**
  2422. * Constructs a new input node.
  2423. *
  2424. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  2425. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2426. */
  2427. constructor( value, nodeType = null ) {
  2428. super( value, nodeType );
  2429. /**
  2430. * This flag can be used for type testing.
  2431. *
  2432. * @type {boolean}
  2433. * @readonly
  2434. * @default true
  2435. */
  2436. this.isConstNode = true;
  2437. }
  2438. /**
  2439. * Generates the shader string of the value with the current node builder.
  2440. *
  2441. * @param {NodeBuilder} builder - The current node builder.
  2442. * @return {string} The generated value as a shader string.
  2443. */
  2444. generateConst( builder ) {
  2445. return builder.generateConst( this.getNodeType( builder ), this.value );
  2446. }
  2447. generate( builder, output ) {
  2448. const type = this.getNodeType( builder );
  2449. if ( _regNum.test( type ) && _regNum.test( output ) ) {
  2450. return builder.generateConst( output, this.value );
  2451. }
  2452. return builder.format( this.generateConst( builder ), type, output );
  2453. }
  2454. }
  2455. /**
  2456. * Base class for representing member access on an object-like
  2457. * node data structures.
  2458. *
  2459. * @augments Node
  2460. */
  2461. class MemberNode extends Node {
  2462. static get type() {
  2463. return 'MemberNode';
  2464. }
  2465. /**
  2466. * Constructs a member node.
  2467. *
  2468. * @param {Node} structNode - The struct node.
  2469. * @param {string} property - The property name.
  2470. */
  2471. constructor( structNode, property ) {
  2472. super();
  2473. /**
  2474. * The struct node.
  2475. *
  2476. * @type {Node}
  2477. */
  2478. this.structNode = structNode;
  2479. /**
  2480. * The property name.
  2481. *
  2482. * @type {Node}
  2483. */
  2484. this.property = property;
  2485. /**
  2486. * This flag can be used for type testing.
  2487. *
  2488. * @type {boolean}
  2489. * @readonly
  2490. * @default true
  2491. */
  2492. this.isMemberNode = true;
  2493. }
  2494. hasMember( builder ) {
  2495. if ( this.structNode.isMemberNode ) {
  2496. if ( this.structNode.hasMember( builder ) === false ) {
  2497. return false;
  2498. }
  2499. }
  2500. return this.structNode.getMemberType( builder, this.property ) !== 'void';
  2501. }
  2502. generateNodeType( builder ) {
  2503. if ( this.hasMember( builder ) === false ) {
  2504. // default type if member does not exist
  2505. return 'float';
  2506. }
  2507. return this.structNode.getMemberType( builder, this.property );
  2508. }
  2509. getMemberType( builder, name ) {
  2510. if ( this.hasMember( builder ) === false ) {
  2511. // default type if member does not exist
  2512. return 'float';
  2513. }
  2514. const type = this.getNodeType( builder );
  2515. const struct = builder.getStructTypeNode( type );
  2516. return struct.getMemberType( builder, name );
  2517. }
  2518. generate( builder ) {
  2519. if ( this.hasMember( builder ) === false ) {
  2520. warn( `TSL: Member "${ this.property }" does not exist in struct.`, this.stackTrace );
  2521. const type = this.getNodeType( builder );
  2522. return builder.generateConst( type );
  2523. }
  2524. const propertyName = this.structNode.build( builder );
  2525. return propertyName + '.' + this.property;
  2526. }
  2527. }
  2528. let currentStack = null;
  2529. const NodeElements = new Map();
  2530. // Extend Node Class for TSL using prototype
  2531. function addMethodChaining( name, nodeElement ) {
  2532. // No require StackTrace because this is internal API
  2533. if ( NodeElements.has( name ) ) {
  2534. warn( `TSL: Redefinition of method chaining '${ name }'.` );
  2535. return;
  2536. }
  2537. if ( typeof nodeElement !== 'function' ) throw new Error( `THREE.TSL: Node element ${ name } is not a function` );
  2538. NodeElements.set( name, nodeElement );
  2539. if ( name !== 'assign' ) {
  2540. // Changing Node prototype to add method chaining
  2541. Node.prototype[ name ] = function ( ...params ) {
  2542. //if ( name === 'toVarIntent' ) return this;
  2543. return this.isStackNode ? this.addToStack( nodeElement( ...params ) ) : nodeElement( this, ...params );
  2544. };
  2545. // Adding assign method chaining
  2546. Node.prototype[ name + 'Assign' ] = function ( ...params ) {
  2547. return this.isStackNode ? this.assign( params[ 0 ], nodeElement( ...params ) ) : this.assign( nodeElement( this, ...params ) );
  2548. };
  2549. }
  2550. }
  2551. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  2552. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  2553. Node.prototype.assign = function ( ...params ) {
  2554. if ( this.isStackNode !== true ) {
  2555. if ( currentStack !== null ) {
  2556. currentStack.assign( this, ...params );
  2557. } else {
  2558. error( 'TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().', new StackTrace() );
  2559. }
  2560. return this;
  2561. } else {
  2562. const nodeElement = NodeElements.get( 'assign' );
  2563. return this.addToStack( nodeElement( ...params ) );
  2564. }
  2565. };
  2566. Node.prototype.toVarIntent = function () {
  2567. return this;
  2568. };
  2569. Node.prototype.get = function ( value ) {
  2570. return new MemberNode( this, value );
  2571. };
  2572. // Cache prototype for TSL
  2573. const proto = {};
  2574. // Set swizzle properties for xyzw, rgba, and stpq.
  2575. function setProtoSwizzle( property, altA, altB ) {
  2576. // swizzle properties
  2577. proto[ property ] = proto[ altA ] = proto[ altB ] = {
  2578. get() {
  2579. this._cache = this._cache || {};
  2580. //
  2581. let split = this._cache[ property ];
  2582. if ( split === undefined ) {
  2583. split = new SplitNode( this, property );
  2584. this._cache[ property ] = split;
  2585. }
  2586. return split;
  2587. },
  2588. set( value ) {
  2589. this[ property ].assign( nodeObject( value ) );
  2590. }
  2591. };
  2592. // set properties ( swizzle ) and sort to xyzw sequence
  2593. const propUpper = property.toUpperCase();
  2594. const altAUpper = altA.toUpperCase();
  2595. const altBUpper = altB.toUpperCase();
  2596. // Set methods for swizzle properties
  2597. Node.prototype[ 'set' + propUpper ] = Node.prototype[ 'set' + altAUpper ] = Node.prototype[ 'set' + altBUpper ] = function ( value ) {
  2598. const swizzle = parseSwizzleAndSort( property );
  2599. return new SetNode( this, swizzle, nodeObject( value ) );
  2600. };
  2601. // Set methods for flip properties
  2602. Node.prototype[ 'flip' + propUpper ] = Node.prototype[ 'flip' + altAUpper ] = Node.prototype[ 'flip' + altBUpper ] = function () {
  2603. const swizzle = parseSwizzleAndSort( property );
  2604. return new FlipNode( this, swizzle );
  2605. };
  2606. }
  2607. const swizzleA = [ 'x', 'y', 'z', 'w' ];
  2608. const swizzleB = [ 'r', 'g', 'b', 'a' ];
  2609. const swizzleC = [ 's', 't', 'p', 'q' ];
  2610. for ( let a = 0; a < 4; a ++ ) {
  2611. let prop = swizzleA[ a ];
  2612. let altA = swizzleB[ a ];
  2613. let altB = swizzleC[ a ];
  2614. setProtoSwizzle( prop, altA, altB );
  2615. for ( let b = 0; b < 4; b ++ ) {
  2616. prop = swizzleA[ a ] + swizzleA[ b ];
  2617. altA = swizzleB[ a ] + swizzleB[ b ];
  2618. altB = swizzleC[ a ] + swizzleC[ b ];
  2619. setProtoSwizzle( prop, altA, altB );
  2620. for ( let c = 0; c < 4; c ++ ) {
  2621. prop = swizzleA[ a ] + swizzleA[ b ] + swizzleA[ c ];
  2622. altA = swizzleB[ a ] + swizzleB[ b ] + swizzleB[ c ];
  2623. altB = swizzleC[ a ] + swizzleC[ b ] + swizzleC[ c ];
  2624. setProtoSwizzle( prop, altA, altB );
  2625. for ( let d = 0; d < 4; d ++ ) {
  2626. prop = swizzleA[ a ] + swizzleA[ b ] + swizzleA[ c ] + swizzleA[ d ];
  2627. altA = swizzleB[ a ] + swizzleB[ b ] + swizzleB[ c ] + swizzleB[ d ];
  2628. altB = swizzleC[ a ] + swizzleC[ b ] + swizzleC[ c ] + swizzleC[ d ];
  2629. setProtoSwizzle( prop, altA, altB );
  2630. }
  2631. }
  2632. }
  2633. }
  2634. // Set/get static properties for array elements (0-31).
  2635. for ( let i = 0; i < 32; i ++ ) {
  2636. proto[ i ] = {
  2637. get() {
  2638. this._cache = this._cache || {};
  2639. //
  2640. let element = this._cache[ i ];
  2641. if ( element === undefined ) {
  2642. element = new ArrayElementNode( this, new ConstNode( i, 'uint' ) );
  2643. this._cache[ i ] = element;
  2644. }
  2645. return element;
  2646. },
  2647. set( value ) {
  2648. this[ i ].assign( nodeObject( value ) );
  2649. }
  2650. };
  2651. }
  2652. /*
  2653. // Set properties for width, height, and depth.
  2654. function setProtoProperty( property, target ) {
  2655. proto[ property ] = {
  2656. get() {
  2657. this._cache = this._cache || {};
  2658. //
  2659. let split = this._cache[ target ];
  2660. if ( split === undefined ) {
  2661. split = new SplitNode( this, target );
  2662. this._cache[ target ] = split;
  2663. }
  2664. return split;
  2665. },
  2666. set( value ) {
  2667. this[ target ].assign( nodeObject( value ) );
  2668. }
  2669. };
  2670. }
  2671. setProtoProperty( 'width', 'x' );
  2672. setProtoProperty( 'height', 'y' );
  2673. setProtoProperty( 'depth', 'z' );
  2674. */
  2675. Object.defineProperties( Node.prototype, proto );
  2676. // --- FINISH ---
  2677. const ShaderNodeObject = function ( obj, altType = null ) {
  2678. const type = getValueType( obj );
  2679. if ( type === 'node' ) {
  2680. return obj;
  2681. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  2682. return nodeObject( getConstNode( obj, altType ) );
  2683. } else if ( type === 'shader' ) {
  2684. return obj.isFn ? obj : Fn( obj );
  2685. }
  2686. return obj;
  2687. };
  2688. const ShaderNodeObjects = function ( objects, altType = null ) {
  2689. for ( const name in objects ) {
  2690. objects[ name ] = nodeObject( objects[ name ], altType );
  2691. }
  2692. return objects;
  2693. };
  2694. const ShaderNodeArray = function ( array, altType = null ) {
  2695. const len = array.length;
  2696. for ( let i = 0; i < len; i ++ ) {
  2697. array[ i ] = nodeObject( array[ i ], altType );
  2698. }
  2699. return array;
  2700. };
  2701. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2702. function assignNode( node ) {
  2703. if ( settings !== null ) {
  2704. node = nodeObject( Object.assign( node, settings ) );
  2705. if ( settings.intent === true ) {
  2706. node = node.toVarIntent();
  2707. }
  2708. } else {
  2709. node = nodeObject( node );
  2710. }
  2711. return node;
  2712. }
  2713. let fn, name = scope, minParams, maxParams;
  2714. function verifyParamsLimit( params ) {
  2715. let tslName;
  2716. if ( name ) tslName = /[a-z]/i.test( name ) ? name + '()' : name;
  2717. else tslName = NodeClass.type;
  2718. if ( minParams !== undefined && params.length < minParams ) {
  2719. error( `TSL: "${ tslName }" parameter length is less than minimum required.`, new StackTrace() );
  2720. return params.concat( new Array( minParams - params.length ).fill( 0 ) );
  2721. } else if ( maxParams !== undefined && params.length > maxParams ) {
  2722. error( `TSL: "${ tslName }" parameter length exceeds limit.`, new StackTrace() );
  2723. return params.slice( 0, maxParams );
  2724. }
  2725. return params;
  2726. }
  2727. if ( scope === null ) {
  2728. fn = ( ...params ) => {
  2729. return assignNode( new NodeClass( ...nodeArray( verifyParamsLimit( params ) ) ) );
  2730. };
  2731. } else if ( factor !== null ) {
  2732. factor = nodeObject( factor );
  2733. fn = ( ...params ) => {
  2734. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ), factor ) );
  2735. };
  2736. } else {
  2737. fn = ( ...params ) => {
  2738. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ) ) );
  2739. };
  2740. }
  2741. fn.setParameterLength = ( ...params ) => {
  2742. if ( params.length === 1 ) minParams = maxParams = params[ 0 ];
  2743. else if ( params.length === 2 ) [ minParams, maxParams ] = params;
  2744. return fn;
  2745. };
  2746. fn.setName = ( value ) => {
  2747. name = value;
  2748. return fn;
  2749. };
  2750. return fn;
  2751. };
  2752. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2753. return new NodeClass( ...nodeArray( params ) );
  2754. };
  2755. class ShaderCallNodeInternal extends Node {
  2756. constructor( shaderNode, rawInputs ) {
  2757. super();
  2758. this.shaderNode = shaderNode;
  2759. this.rawInputs = rawInputs;
  2760. this.isShaderCallNodeInternal = true;
  2761. }
  2762. generateNodeType( builder ) {
  2763. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2764. }
  2765. getElementType( builder ) {
  2766. return this.getOutputNode( builder ).getElementType( builder );
  2767. }
  2768. getMemberType( builder, name ) {
  2769. return this.getOutputNode( builder ).getMemberType( builder, name );
  2770. }
  2771. call( builder ) {
  2772. const { shaderNode, rawInputs } = this;
  2773. const properties = builder.getNodeProperties( shaderNode );
  2774. const subBuild = builder.getClosestSubBuild( shaderNode.subBuilds ) || '';
  2775. const subBuildProperty = subBuild || 'default';
  2776. if ( properties[ subBuildProperty ] ) {
  2777. return properties[ subBuildProperty ];
  2778. }
  2779. //
  2780. const previousSubBuildFn = builder.subBuildFn;
  2781. const previousFnCall = builder.fnCall;
  2782. builder.subBuildFn = subBuild;
  2783. builder.fnCall = this;
  2784. let result = null;
  2785. if ( shaderNode.layout ) {
  2786. // build inputs first
  2787. if ( rawInputs ) {
  2788. // use layout inputs to ensure that no extra parameters are built
  2789. const inputs = shaderNode.layout.inputs;
  2790. if ( isArrayAsParameter( rawInputs ) ) {
  2791. const rawArrayParameters = rawInputs;
  2792. for ( let i = 0; i < inputs.length; i ++ ) {
  2793. const rawParameter = rawArrayParameters[ i ];
  2794. if ( rawParameter && rawParameter.isNode ) {
  2795. rawParameter.build( builder );
  2796. }
  2797. }
  2798. } else {
  2799. const rawObjectParameters = rawInputs[ 0 ];
  2800. for ( const param of inputs ) {
  2801. const rawParameter = rawObjectParameters[ param.name ];
  2802. if ( rawParameter && rawParameter.isNode ) {
  2803. rawParameter.build( builder );
  2804. }
  2805. }
  2806. }
  2807. }
  2808. const functionNode = builder.buildFunctionNode( shaderNode );
  2809. builder.addInclude( functionNode );
  2810. //
  2811. const inputs = rawInputs ? getLayoutParameters( rawInputs ) : null;
  2812. result = functionNode.call( inputs );
  2813. } else {
  2814. const secureNodeBuilder = new Proxy( builder, {
  2815. get: ( target, property, receiver ) => {
  2816. let value;
  2817. if ( Symbol.iterator === property ) {
  2818. value = function* () {
  2819. yield undefined;
  2820. };
  2821. } else {
  2822. value = Reflect.get( target, property, receiver );
  2823. }
  2824. return value;
  2825. }
  2826. } );
  2827. //
  2828. const inputs = rawInputs ? getProxyParameters( rawInputs ) : null;
  2829. const hasParameters = Array.isArray( rawInputs ) ? rawInputs.length > 0 : rawInputs !== null;
  2830. const jsFunc = shaderNode.jsFunc;
  2831. const outputNode = hasParameters || jsFunc.length > 1 ? jsFunc( inputs, secureNodeBuilder ) : jsFunc( secureNodeBuilder );
  2832. result = nodeObject( outputNode );
  2833. }
  2834. builder.subBuildFn = previousSubBuildFn;
  2835. builder.fnCall = previousFnCall;
  2836. if ( shaderNode.once ) {
  2837. properties[ subBuildProperty ] = result;
  2838. }
  2839. return result;
  2840. }
  2841. setupOutput( builder ) {
  2842. builder.addStack();
  2843. builder.stack.outputNode = this.call( builder );
  2844. return builder.removeStack();
  2845. }
  2846. getOutputNode( builder ) {
  2847. const properties = builder.getNodeProperties( this );
  2848. const subBuildOutput = builder.getSubBuildOutput( this );
  2849. properties[ subBuildOutput ] = properties[ subBuildOutput ] || this.setupOutput( builder );
  2850. properties[ subBuildOutput ].subBuild = builder.getClosestSubBuild( this );
  2851. return properties[ subBuildOutput ];
  2852. }
  2853. build( builder, output = null ) {
  2854. let result = null;
  2855. const buildStage = builder.getBuildStage();
  2856. const properties = builder.getNodeProperties( this );
  2857. const subBuildOutput = builder.getSubBuildOutput( this );
  2858. const outputNode = this.getOutputNode( builder );
  2859. const previousFnCall = builder.fnCall;
  2860. builder.fnCall = this;
  2861. if ( buildStage === 'setup' ) {
  2862. const subBuildInitialized = builder.getSubBuildProperty( 'initialized', this );
  2863. if ( properties[ subBuildInitialized ] !== true ) {
  2864. properties[ subBuildInitialized ] = true;
  2865. properties[ subBuildOutput ] = this.getOutputNode( builder );
  2866. properties[ subBuildOutput ].build( builder );
  2867. // If the shaderNode has subBuilds, add them to the chaining nodes
  2868. // so they can be built later in the build process.
  2869. if ( this.shaderNode.subBuilds ) {
  2870. for ( const node of builder.chaining ) {
  2871. const nodeData = builder.getDataFromNode( node, 'any' );
  2872. nodeData.subBuilds = nodeData.subBuilds || new Set();
  2873. for ( const subBuild of this.shaderNode.subBuilds ) {
  2874. nodeData.subBuilds.add( subBuild );
  2875. }
  2876. //builder.getDataFromNode( node ).subBuilds = nodeData.subBuilds;
  2877. }
  2878. }
  2879. }
  2880. result = properties[ subBuildOutput ];
  2881. } else if ( buildStage === 'analyze' ) {
  2882. outputNode.build( builder, output );
  2883. } else if ( buildStage === 'generate' ) {
  2884. result = outputNode.build( builder, output ) || '';
  2885. }
  2886. builder.fnCall = previousFnCall;
  2887. return result;
  2888. }
  2889. }
  2890. function isArrayAsParameter( params ) {
  2891. return params[ 0 ] && ( params[ 0 ].isNode || Object.getPrototypeOf( params[ 0 ] ) !== Object.prototype );
  2892. }
  2893. function getLayoutParameters( params ) {
  2894. let output;
  2895. nodeObjects( params );
  2896. if ( isArrayAsParameter( params ) ) {
  2897. output = [ ...params ];
  2898. } else {
  2899. output = params[ 0 ];
  2900. }
  2901. return output;
  2902. }
  2903. function getProxyParameters( params ) {
  2904. let index = 0;
  2905. nodeObjects( params );
  2906. return new Proxy( params, {
  2907. get: ( target, property, receiver ) => {
  2908. let value;
  2909. if ( property === 'length' ) {
  2910. value = params.length;
  2911. return value;
  2912. }
  2913. if ( Symbol.iterator === property ) {
  2914. value = function* () {
  2915. for ( const inputNode of params ) {
  2916. yield nodeObject( inputNode );
  2917. }
  2918. };
  2919. } else {
  2920. if ( params.length > 0 ) {
  2921. if ( Object.getPrototypeOf( params[ 0 ] ) === Object.prototype ) {
  2922. const objectTarget = params[ 0 ];
  2923. if ( objectTarget[ property ] === undefined ) {
  2924. value = objectTarget[ index ++ ];
  2925. } else {
  2926. value = Reflect.get( objectTarget, property, receiver );
  2927. }
  2928. } else if ( params[ 0 ] instanceof Node ) {
  2929. if ( params[ property ] === undefined ) {
  2930. value = params[ index ++ ];
  2931. } else {
  2932. value = Reflect.get( params, property, receiver );
  2933. }
  2934. }
  2935. } else {
  2936. value = Reflect.get( target, property, receiver );
  2937. }
  2938. value = nodeObject( value );
  2939. }
  2940. return value;
  2941. }
  2942. } );
  2943. }
  2944. class ShaderNodeInternal extends Node {
  2945. constructor( jsFunc, nodeType ) {
  2946. super( nodeType );
  2947. this.jsFunc = jsFunc;
  2948. this.layout = null;
  2949. this.global = true;
  2950. this.once = false;
  2951. }
  2952. setLayout( layout ) {
  2953. this.layout = layout;
  2954. return this;
  2955. }
  2956. getLayout() {
  2957. return this.layout;
  2958. }
  2959. call( rawInputs = null ) {
  2960. return new ShaderCallNodeInternal( this, rawInputs );
  2961. }
  2962. setup() {
  2963. return this.call();
  2964. }
  2965. }
  2966. const bools = [ false, true ];
  2967. const uints = [ 0, 1, 2, 3 ];
  2968. const ints = [ -1, -2 ];
  2969. 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 ];
  2970. const boolsCacheMap = new Map();
  2971. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2972. const uintsCacheMap = new Map();
  2973. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2974. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2975. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2976. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2977. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2978. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2979. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2980. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2981. const getConstNode = ( value, type ) => {
  2982. if ( constNodesCacheMap.has( value ) ) {
  2983. return constNodesCacheMap.get( value );
  2984. } else if ( value.isNode === true ) {
  2985. return value;
  2986. } else {
  2987. return new ConstNode( value, type );
  2988. }
  2989. };
  2990. const ConvertType = function ( type, cacheMap = null ) {
  2991. return ( ...params ) => {
  2992. for ( const param of params ) {
  2993. if ( param === undefined ) {
  2994. error( `TSL: Invalid parameter for the type "${ type }".`, new StackTrace() );
  2995. return new ConstNode( 0, type );
  2996. }
  2997. }
  2998. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => {
  2999. const paramType = typeof param;
  3000. return paramType !== 'object' && paramType !== 'function';
  3001. } ) ) ) {
  3002. params = [ getValueFromType( type, ...params ) ];
  3003. }
  3004. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  3005. return nodeObjectIntent( cacheMap.get( params[ 0 ] ) );
  3006. }
  3007. if ( params.length === 1 ) {
  3008. const node = getConstNode( params[ 0 ], type );
  3009. if ( node.nodeType === type ) return nodeObjectIntent( node );
  3010. return nodeObjectIntent( new ConvertNode( node, type ) );
  3011. }
  3012. const nodes = params.map( param => getConstNode( param ) );
  3013. return nodeObjectIntent( new JoinNode( nodes, type ) );
  3014. };
  3015. };
  3016. // exports
  3017. function defined( value ) {
  3018. if ( value && value.isNode ) {
  3019. value.traverse( ( node ) => {
  3020. if ( node.isConstNode ) {
  3021. value = node.value;
  3022. }
  3023. } );
  3024. }
  3025. return Boolean( value );
  3026. }
  3027. // utils
  3028. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  3029. // shader node base
  3030. function ShaderNode( jsFunc, nodeType ) {
  3031. return new ShaderNodeInternal( jsFunc, nodeType );
  3032. }
  3033. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  3034. const nodeObjectIntent = ( val, altType = null ) => /* new */ nodeObject( val, altType ).toVarIntent();
  3035. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  3036. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  3037. const nodeProxy = ( NodeClass, scope = null, factor = null, settings = null ) => new ShaderNodeProxy( NodeClass, scope, factor, settings );
  3038. const nodeImmutable = ( NodeClass, ...params ) => new ShaderNodeImmutable( NodeClass, ...params );
  3039. const nodeProxyIntent = ( NodeClass, scope = null, factor = null, settings = {} ) => new ShaderNodeProxy( NodeClass, scope, factor, { ...settings, intent: true } );
  3040. const nodeProxyConstructor = ( constructorFunction, nodeInstance ) => {
  3041. return new Proxy( constructorFunction, {
  3042. get( target, prop, receiver ) {
  3043. return Reflect.get( nodeInstance, prop, receiver );
  3044. },
  3045. set( target, prop, value ) {
  3046. return Reflect.set( nodeInstance, prop, value );
  3047. }
  3048. } );
  3049. };
  3050. let fnId = 0;
  3051. class FnNode extends Node {
  3052. constructor( jsFunc, layout = null ) {
  3053. super();
  3054. let nodeType = null;
  3055. if ( layout !== null ) {
  3056. if ( typeof layout === 'object' ) {
  3057. nodeType = layout.return;
  3058. } else {
  3059. if ( typeof layout === 'string' ) {
  3060. nodeType = layout;
  3061. } else {
  3062. error( 'TSL: Invalid layout type.', new StackTrace() );
  3063. }
  3064. layout = null;
  3065. }
  3066. }
  3067. this.shaderNode = new ShaderNode( jsFunc, nodeType );
  3068. if ( layout !== null ) {
  3069. this.setLayout( layout );
  3070. }
  3071. this.isFn = true;
  3072. }
  3073. setLayout( layout ) {
  3074. const nodeType = this.shaderNode.nodeType;
  3075. if ( typeof layout.inputs !== 'object' ) {
  3076. const fullLayout = {
  3077. name: 'fn' + fnId ++,
  3078. type: nodeType,
  3079. inputs: []
  3080. };
  3081. for ( const name in layout ) {
  3082. if ( name === 'return' ) continue;
  3083. fullLayout.inputs.push( {
  3084. name: name,
  3085. type: layout[ name ]
  3086. } );
  3087. }
  3088. layout = fullLayout;
  3089. }
  3090. this.shaderNode.setLayout( layout );
  3091. return this;
  3092. }
  3093. generateNodeType( builder ) {
  3094. return this.shaderNode.getNodeType( builder ) || 'float';
  3095. }
  3096. call( ...params ) {
  3097. const fnCall = this.shaderNode.call( params );
  3098. if ( this.shaderNode.nodeType === 'void' ) fnCall.toStack();
  3099. return fnCall.toVarIntent();
  3100. }
  3101. once( subBuilds = null ) {
  3102. this.shaderNode.once = true;
  3103. this.shaderNode.subBuilds = subBuilds;
  3104. return this;
  3105. }
  3106. generate( builder ) {
  3107. const type = this.getNodeType( builder );
  3108. error( 'TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".', this.stackTrace );
  3109. return builder.generateConst( type );
  3110. }
  3111. }
  3112. function Fn( jsFunc, layout = null ) {
  3113. const instance = new FnNode( jsFunc, layout );
  3114. return new Proxy( () => {}, {
  3115. apply( target, thisArg, params ) {
  3116. return instance.call( ...params );
  3117. },
  3118. get( target, prop, receiver ) {
  3119. return Reflect.get( instance, prop, receiver );
  3120. },
  3121. set( target, prop, value, receiver ) {
  3122. return Reflect.set( instance, prop, value, receiver );
  3123. }
  3124. } );
  3125. }
  3126. //
  3127. const setCurrentStack = ( stack ) => {
  3128. currentStack = stack;
  3129. };
  3130. const getCurrentStack = () => currentStack;
  3131. /**
  3132. * Represent a conditional node using if/else statements.
  3133. *
  3134. * ```js
  3135. * If( condition, function )
  3136. * .ElseIf( condition, function )
  3137. * .Else( function )
  3138. * ```
  3139. * @tsl
  3140. * @function
  3141. * @param {...any} params - The parameters for the conditional node.
  3142. * @returns {StackNode} The conditional node.
  3143. */
  3144. const If = ( ...params ) => currentStack.If( ...params );
  3145. /**
  3146. * Represent a conditional node using switch/case statements.
  3147. *
  3148. * ```js
  3149. * Switch( value )
  3150. * .Case( 1, function )
  3151. * .Case( 2, 3, 4, function )
  3152. * .Default( function )
  3153. * ```
  3154. * @tsl
  3155. * @function
  3156. * @param {...any} params - The parameters for the conditional node.
  3157. * @returns {StackNode} The conditional node.
  3158. */
  3159. const Switch = ( ...params ) => currentStack.Switch( ...params );
  3160. /**
  3161. * Add the given node to the current stack.
  3162. *
  3163. * @param {Node} node - The node to add.
  3164. * @returns {Node} The node that was added to the stack.
  3165. */
  3166. function Stack( node ) {
  3167. if ( currentStack ) currentStack.addToStack( node );
  3168. return node;
  3169. }
  3170. addMethodChaining( 'toStack', Stack );
  3171. // types
  3172. const color = new ConvertType( 'color' );
  3173. const float = new ConvertType( 'float', cacheMaps.float );
  3174. const int = new ConvertType( 'int', cacheMaps.ints );
  3175. const uint = new ConvertType( 'uint', cacheMaps.uint );
  3176. const bool = new ConvertType( 'bool', cacheMaps.bool );
  3177. const vec2 = new ConvertType( 'vec2' );
  3178. const ivec2 = new ConvertType( 'ivec2' );
  3179. const uvec2 = new ConvertType( 'uvec2' );
  3180. const bvec2 = new ConvertType( 'bvec2' );
  3181. const vec3 = new ConvertType( 'vec3' );
  3182. const ivec3 = new ConvertType( 'ivec3' );
  3183. const uvec3 = new ConvertType( 'uvec3' );
  3184. const bvec3 = new ConvertType( 'bvec3' );
  3185. const vec4 = new ConvertType( 'vec4' );
  3186. const ivec4 = new ConvertType( 'ivec4' );
  3187. const uvec4 = new ConvertType( 'uvec4' );
  3188. const bvec4 = new ConvertType( 'bvec4' );
  3189. const mat2 = new ConvertType( 'mat2' );
  3190. const mat3 = new ConvertType( 'mat3' );
  3191. const mat4 = new ConvertType( 'mat4' );
  3192. addMethodChaining( 'toColor', color );
  3193. addMethodChaining( 'toFloat', float );
  3194. addMethodChaining( 'toInt', int );
  3195. addMethodChaining( 'toUint', uint );
  3196. addMethodChaining( 'toBool', bool );
  3197. addMethodChaining( 'toVec2', vec2 );
  3198. addMethodChaining( 'toIVec2', ivec2 );
  3199. addMethodChaining( 'toUVec2', uvec2 );
  3200. addMethodChaining( 'toBVec2', bvec2 );
  3201. addMethodChaining( 'toVec3', vec3 );
  3202. addMethodChaining( 'toIVec3', ivec3 );
  3203. addMethodChaining( 'toUVec3', uvec3 );
  3204. addMethodChaining( 'toBVec3', bvec3 );
  3205. addMethodChaining( 'toVec4', vec4 );
  3206. addMethodChaining( 'toIVec4', ivec4 );
  3207. addMethodChaining( 'toUVec4', uvec4 );
  3208. addMethodChaining( 'toBVec4', bvec4 );
  3209. addMethodChaining( 'toMat2', mat2 );
  3210. addMethodChaining( 'toMat3', mat3 );
  3211. addMethodChaining( 'toMat4', mat4 );
  3212. // basic nodes
  3213. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode ).setParameterLength( 2 );
  3214. const convert = ( node, types ) => new ConvertNode( nodeObject( node ), types );
  3215. const split = ( node, channels ) => new SplitNode( nodeObject( node ), channels );
  3216. addMethodChaining( 'element', element );
  3217. addMethodChaining( 'convert', convert );
  3218. /**
  3219. * This class represents a shader property. It can be used
  3220. * to explicitly define a property and assign a value to it.
  3221. *
  3222. * ```js
  3223. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  3224. *```
  3225. * `PropertyNode` is used by the engine to predefined common material properties
  3226. * for TSL code.
  3227. *
  3228. * @augments Node
  3229. */
  3230. class PropertyNode extends Node {
  3231. static get type() {
  3232. return 'PropertyNode';
  3233. }
  3234. /**
  3235. * Constructs a new property node.
  3236. *
  3237. * @param {string} nodeType - The type of the node.
  3238. * @param {?string} [name=null] - The name of the property in the shader.
  3239. * @param {boolean} [varying=false] - Whether this property is a varying or not.
  3240. * @param {?Node} [placeholderNode=null] - The placeholder node if not assigned.
  3241. */
  3242. constructor( nodeType, name = null, varying = false, placeholderNode = null ) {
  3243. super( nodeType );
  3244. /**
  3245. * The name of the property in the shader. If no name is defined,
  3246. * the node system auto-generates one.
  3247. *
  3248. * @type {?string}
  3249. * @default null
  3250. */
  3251. this.name = name;
  3252. /**
  3253. * Whether this property is a varying or not.
  3254. *
  3255. * @type {boolean}
  3256. * @default false
  3257. */
  3258. this.varying = varying;
  3259. /**
  3260. * The placeholder node of the property if it is not assigned.
  3261. *
  3262. * @type {?Node}
  3263. * @default null
  3264. */
  3265. this.placeholderNode = nodeObject( placeholderNode );
  3266. /**
  3267. * This flag can be used for type testing.
  3268. *
  3269. * @type {boolean}
  3270. * @readonly
  3271. * @default true
  3272. */
  3273. this.isPropertyNode = true;
  3274. /**
  3275. * This flag is used for global cache.
  3276. *
  3277. * @type {boolean}
  3278. * @default true
  3279. */
  3280. this.global = true;
  3281. }
  3282. getNodeType( builder ) {
  3283. const nodeType = super.getNodeType( builder );
  3284. if ( nodeType === 'output' ) {
  3285. return builder.getOutputType();
  3286. }
  3287. return nodeType;
  3288. }
  3289. customCacheKey() {
  3290. return hashString( this.type + ':' + ( this.name || '' ) + ':' + ( this.varying ? '1' : '0' ) );
  3291. }
  3292. getHash( builder ) {
  3293. return this.name || super.getHash( builder );
  3294. }
  3295. generate( builder ) {
  3296. let nodeVar;
  3297. if ( this.varying === true ) {
  3298. nodeVar = builder.getVaryingFromNode( this, this.name );
  3299. nodeVar.needsInterpolation = true;
  3300. } else {
  3301. nodeVar = builder.getVarFromNode( this, this.name );
  3302. if ( this.placeholderNode !== null ) {
  3303. if ( builder.hasWriteUsage( this ) === false ) {
  3304. const snippet = this.placeholderNode.build( builder, this.getNodeType( builder ) );
  3305. builder.addLineFlowCode( `${ builder.getPropertyName( nodeVar ) } = ${ snippet }`, this );
  3306. }
  3307. }
  3308. }
  3309. return builder.getPropertyName( nodeVar );
  3310. }
  3311. }
  3312. /**
  3313. * TSL function for creating a property node.
  3314. *
  3315. * @tsl
  3316. * @function
  3317. * @param {string} type - The type of the node.
  3318. * @param {?string} [name=null] - The name of the property in the shader.
  3319. * @param {?Node} [placeholderNode=null] - The placeholder node if not assigned.
  3320. * @returns {PropertyNode}
  3321. */
  3322. const property = ( type, name, placeholderNode = null ) => new PropertyNode( type, name, false, placeholderNode );
  3323. /**
  3324. * TSL function for creating a varying property node.
  3325. *
  3326. * @tsl
  3327. * @function
  3328. * @param {string} type - The type of the node.
  3329. * @param {?string} [name=null] - The name of the varying in the shader.
  3330. * @param {?Node} [placeholderNode=null] - The placeholder node if not assigned.
  3331. * @returns {PropertyNode}
  3332. */
  3333. const varyingProperty = ( type, name, placeholderNode = null ) => new PropertyNode( type, name, true, placeholderNode );
  3334. /**
  3335. * TSL object that represents the shader variable `DiffuseColor`.
  3336. *
  3337. * @tsl
  3338. * @type {PropertyNode<vec4>}
  3339. */
  3340. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  3341. /**
  3342. * TSL object that represents the shader variable `DiffuseContribution`.
  3343. *
  3344. * @tsl
  3345. * @type {PropertyNode<vec3>}
  3346. */
  3347. const diffuseContribution = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'DiffuseContribution' );
  3348. /**
  3349. * TSL object that represents the shader variable `EmissiveColor`.
  3350. *
  3351. * @tsl
  3352. * @type {PropertyNode<vec3>}
  3353. */
  3354. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  3355. /**
  3356. * TSL object that represents the shader variable `Roughness`.
  3357. *
  3358. * @tsl
  3359. * @type {PropertyNode<float>}
  3360. */
  3361. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  3362. /**
  3363. * TSL object that represents the shader variable `Metalness`.
  3364. *
  3365. * @tsl
  3366. * @type {PropertyNode<float>}
  3367. */
  3368. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  3369. /**
  3370. * TSL object that represents the shader variable `Clearcoat`.
  3371. *
  3372. * @tsl
  3373. * @type {PropertyNode<float>}
  3374. */
  3375. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  3376. /**
  3377. * TSL object that represents the shader variable `ClearcoatRoughness`.
  3378. *
  3379. * @tsl
  3380. * @type {PropertyNode<float>}
  3381. */
  3382. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  3383. /**
  3384. * TSL object that represents the shader variable `Sheen`.
  3385. *
  3386. * @tsl
  3387. * @type {PropertyNode<vec3>}
  3388. */
  3389. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  3390. /**
  3391. * TSL object that represents the shader variable `SheenRoughness`.
  3392. *
  3393. * @tsl
  3394. * @type {PropertyNode<float>}
  3395. */
  3396. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  3397. /**
  3398. * TSL object that represents the shader variable `Iridescence`.
  3399. *
  3400. * @tsl
  3401. * @type {PropertyNode<float>}
  3402. */
  3403. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  3404. /**
  3405. * TSL object that represents the shader variable `IridescenceIOR`.
  3406. *
  3407. * @tsl
  3408. * @type {PropertyNode<float>}
  3409. */
  3410. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  3411. /**
  3412. * TSL object that represents the shader variable `IridescenceThickness`.
  3413. *
  3414. * @tsl
  3415. * @type {PropertyNode<float>}
  3416. */
  3417. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  3418. /**
  3419. * TSL object that represents the shader variable `AlphaT`.
  3420. *
  3421. * @tsl
  3422. * @type {PropertyNode<float>}
  3423. */
  3424. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  3425. /**
  3426. * TSL object that represents the shader variable `Anisotropy`.
  3427. *
  3428. * @tsl
  3429. * @type {PropertyNode<float>}
  3430. */
  3431. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  3432. /**
  3433. * TSL object that represents the shader variable `AnisotropyT`.
  3434. *
  3435. * @tsl
  3436. * @type {PropertyNode<vec3>}
  3437. */
  3438. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  3439. /**
  3440. * TSL object that represents the shader variable `AnisotropyB`.
  3441. *
  3442. * @tsl
  3443. * @type {PropertyNode<vec3>}
  3444. */
  3445. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  3446. /**
  3447. * TSL object that represents the shader variable `SpecularColor`.
  3448. *
  3449. * @tsl
  3450. * @type {PropertyNode<color>}
  3451. */
  3452. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  3453. /**
  3454. * TSL object that represents the shader variable `SpecularColorBlended`.
  3455. *
  3456. * @tsl
  3457. * @type {PropertyNode<color>}
  3458. */
  3459. const specularColorBlended = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColorBlended' );
  3460. /**
  3461. * TSL object that represents the shader variable `SpecularF90`.
  3462. *
  3463. * @tsl
  3464. * @type {PropertyNode<float>}
  3465. */
  3466. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  3467. /**
  3468. * TSL object that represents the shader variable `Shininess`.
  3469. *
  3470. * @tsl
  3471. * @type {PropertyNode<float>}
  3472. */
  3473. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  3474. /**
  3475. * TSL object that represents the shader variable `Output`.
  3476. *
  3477. * @tsl
  3478. * @type {PropertyNode<vec4>}
  3479. */
  3480. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'output', 'Output' );
  3481. /**
  3482. * TSL object that represents the shader variable `dashSize`.
  3483. *
  3484. * @tsl
  3485. * @type {PropertyNode<float>}
  3486. */
  3487. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  3488. /**
  3489. * TSL object that represents the shader variable `gapSize`.
  3490. *
  3491. * @tsl
  3492. * @type {PropertyNode<float>}
  3493. */
  3494. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  3495. /**
  3496. * TSL object that represents the shader variable `pointWidth`.
  3497. *
  3498. * @tsl
  3499. * @type {PropertyNode<float>}
  3500. */
  3501. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  3502. /**
  3503. * TSL object that represents the shader variable `IOR`.
  3504. *
  3505. * @tsl
  3506. * @type {PropertyNode<float>}
  3507. */
  3508. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  3509. /**
  3510. * TSL object that represents the shader variable `Transmission`.
  3511. *
  3512. * @tsl
  3513. * @type {PropertyNode<float>}
  3514. */
  3515. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  3516. /**
  3517. * TSL object that represents the shader variable `Thickness`.
  3518. *
  3519. * @tsl
  3520. * @type {PropertyNode<float>}
  3521. */
  3522. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  3523. /**
  3524. * TSL object that represents the shader variable `AttenuationDistance`.
  3525. *
  3526. * @tsl
  3527. * @type {PropertyNode<float>}
  3528. */
  3529. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  3530. /**
  3531. * TSL object that represents the shader variable `AttenuationColor`.
  3532. *
  3533. * @tsl
  3534. * @type {PropertyNode<color>}
  3535. */
  3536. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  3537. /**
  3538. * TSL object that represents the shader variable `Dispersion`.
  3539. *
  3540. * @tsl
  3541. * @type {PropertyNode<float>}
  3542. */
  3543. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  3544. /**
  3545. * TSL object that represents the shader variable `Retroreflective`.
  3546. *
  3547. * @tsl
  3548. * @type {PropertyNode<float>}
  3549. */
  3550. const retroreflective = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Retroreflective' );
  3551. /**
  3552. * TSL object that represents the shader variable `AmbientOcclusion`.
  3553. * If no value is assigned to this property, it defaults to a placeholder value of `1.0`.
  3554. *
  3555. * @tsl
  3556. * @type {PropertyNode<float>}
  3557. */
  3558. const ambientOcclusion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AmbientOcclusion', false, 1 );
  3559. /**
  3560. * This node can be used to group single instances of {@link UniformNode}
  3561. * and manage them as a uniform buffer.
  3562. *
  3563. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  3564. * will be used when defining the {@link UniformNode#groupNode} property.
  3565. *
  3566. * - `objectGroup`: Uniform buffer per object.
  3567. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  3568. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  3569. *
  3570. * @augments Node
  3571. */
  3572. class UniformGroupNode extends Node {
  3573. static get type() {
  3574. return 'UniformGroupNode';
  3575. }
  3576. /**
  3577. * Constructs a new uniform group node.
  3578. *
  3579. * @param {string} name - The name of the uniform group node.
  3580. * @param {boolean} [shared=false] - Whether this uniform group node is shared or not.
  3581. * @param {number} [order=1] - Influences the internal sorting.
  3582. * @param {string|null} [updateType=null] - The update type of the uniform group node.
  3583. */
  3584. constructor( name, shared = false, order = 1, updateType = null ) {
  3585. super( 'string' );
  3586. /**
  3587. * The name of the uniform group node.
  3588. *
  3589. * @type {string}
  3590. */
  3591. this.name = name;
  3592. /**
  3593. * Whether this uniform group node is shared or not.
  3594. *
  3595. * @type {boolean}
  3596. * @default false
  3597. */
  3598. this.shared = shared;
  3599. /**
  3600. * Influences the internal sorting.
  3601. * TODO: Add details when this property should be changed.
  3602. *
  3603. * @type {number}
  3604. * @default 1
  3605. */
  3606. this.order = order;
  3607. /**
  3608. * The update type of the uniform group node.
  3609. *
  3610. * @type {string|null}
  3611. * @default null
  3612. */
  3613. this.updateType = updateType;
  3614. /**
  3615. * This flag can be used for type testing.
  3616. *
  3617. * @type {boolean}
  3618. * @readonly
  3619. * @default true
  3620. */
  3621. this.isUniformGroup = true;
  3622. }
  3623. /**
  3624. * Marks the uniform group node as needing an update.
  3625. * This will trigger the necessary updates in the rendering process.
  3626. */
  3627. update() {
  3628. this.needsUpdate = true;
  3629. }
  3630. /**
  3631. * Serializes the uniform group node to a JSON object.
  3632. *
  3633. * @param {Object} data - The object to store the serialized data.
  3634. */
  3635. serialize( data ) {
  3636. super.serialize( data );
  3637. data.name = this.name;
  3638. data.version = this.version;
  3639. data.shared = this.shared;
  3640. }
  3641. /**
  3642. * Deserializes the uniform group node from a JSON object.
  3643. *
  3644. * @param {Object} data - The object containing the serialized data.
  3645. */
  3646. deserialize( data ) {
  3647. super.deserialize( data );
  3648. this.name = data.name;
  3649. this.version = data.version;
  3650. this.shared = data.shared;
  3651. }
  3652. }
  3653. /**
  3654. * TSL function for creating a uniform group node with the given name.
  3655. *
  3656. * @tsl
  3657. * @function
  3658. * @param {string} name - The name of the uniform group node.
  3659. * @returns {UniformGroupNode}
  3660. */
  3661. const uniformGroup = ( name, order = 1, updateType = null ) => new UniformGroupNode( name, false, order, updateType );
  3662. /**
  3663. * TSL function for creating a shared uniform group node with the given name and order.
  3664. *
  3665. * @tsl
  3666. * @function
  3667. * @param {string} name - The name of the uniform group node.
  3668. * @param {number} [order=0] - Influences the internal sorting.
  3669. * @returns {UniformGroupNode}
  3670. */
  3671. const sharedUniformGroup = ( name, order = 0, updateType = null ) => new UniformGroupNode( name, true, order, updateType );
  3672. /**
  3673. * TSL object that represents a shared uniform group node which is updated once per frame.
  3674. *
  3675. * @tsl
  3676. * @type {UniformGroupNode}
  3677. */
  3678. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame', 0, NodeUpdateType.FRAME );
  3679. /**
  3680. * TSL object that represents a shared uniform group node which is updated once per render.
  3681. *
  3682. * @tsl
  3683. * @type {UniformGroupNode}
  3684. */
  3685. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render', 0, NodeUpdateType.RENDER );
  3686. /**
  3687. * TSL object that represents a uniform group node which is updated once per object.
  3688. *
  3689. * @tsl
  3690. * @type {UniformGroupNode}
  3691. */
  3692. const objectGroup = /*@__PURE__*/ uniformGroup( 'object', 1, NodeUpdateType.OBJECT );
  3693. /**
  3694. * Class for representing a uniform.
  3695. *
  3696. * @augments InputNode
  3697. */
  3698. class UniformNode extends InputNode {
  3699. static get type() {
  3700. return 'UniformNode';
  3701. }
  3702. /**
  3703. * Constructs a new uniform node.
  3704. *
  3705. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3706. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3707. */
  3708. constructor( value, nodeType = null ) {
  3709. super( value, nodeType );
  3710. /**
  3711. * This flag can be used for type testing.
  3712. *
  3713. * @type {boolean}
  3714. * @readonly
  3715. * @default true
  3716. */
  3717. this.isUniformNode = true;
  3718. /**
  3719. * The name or label of the uniform.
  3720. *
  3721. * @type {string}
  3722. * @default ''
  3723. */
  3724. this.name = '';
  3725. /**
  3726. * The uniform group of this uniform. By default, uniforms are
  3727. * managed per object but they might belong to a shared group
  3728. * which is updated per frame or render call.
  3729. *
  3730. * @type {UniformGroupNode}
  3731. */
  3732. this.groupNode = objectGroup;
  3733. }
  3734. /**
  3735. * Sets the {@link UniformNode#name} property.
  3736. *
  3737. * @param {string} name - The name of the uniform.
  3738. * @return {UniformNode} A reference to this node.
  3739. */
  3740. setName( name ) {
  3741. this.name = name;
  3742. return this;
  3743. }
  3744. /**
  3745. * Sets the {@link UniformNode#name} property.
  3746. *
  3747. * @deprecated
  3748. * @param {string} name - The name of the uniform.
  3749. * @return {UniformNode} A reference to this node.
  3750. */
  3751. label( name ) {
  3752. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.', new StackTrace() ); // @deprecated r179
  3753. return this.setName( name );
  3754. }
  3755. /**
  3756. * Sets the {@link UniformNode#groupNode} property.
  3757. *
  3758. * @param {UniformGroupNode} group - The uniform group.
  3759. * @return {UniformNode} A reference to this node.
  3760. */
  3761. setGroup( group ) {
  3762. this.groupNode = group;
  3763. return this;
  3764. }
  3765. /**
  3766. * Returns the {@link UniformNode#groupNode}.
  3767. *
  3768. * @return {UniformGroupNode} The uniform group.
  3769. */
  3770. getGroup() {
  3771. return this.groupNode;
  3772. }
  3773. /**
  3774. * By default, this method returns the result of {@link Node#getHash} but derived
  3775. * classes might overwrite this method with a different implementation.
  3776. *
  3777. * @param {NodeBuilder} builder - The current node builder.
  3778. * @return {string} The uniform hash.
  3779. */
  3780. getUniformHash( builder ) {
  3781. return this.getHash( builder );
  3782. }
  3783. onUpdate( callback, updateType ) {
  3784. callback = callback.bind( this );
  3785. return super.onUpdate( ( frame ) => {
  3786. const value = callback( frame, this );
  3787. if ( value !== undefined ) {
  3788. this.value = value;
  3789. }
  3790. }, updateType );
  3791. }
  3792. getInputType( builder ) {
  3793. let type = super.getInputType( builder );
  3794. if ( type === 'bool' ) {
  3795. type = 'uint';
  3796. }
  3797. return type;
  3798. }
  3799. generate( builder, output ) {
  3800. const type = this.getNodeType( builder );
  3801. const hash = this.getUniformHash( builder );
  3802. let sharedNode = builder.getNodeFromHash( hash );
  3803. if ( sharedNode === undefined ) {
  3804. builder.setHashNode( this, hash );
  3805. sharedNode = this;
  3806. }
  3807. const sharedNodeType = sharedNode.getInputType( builder );
  3808. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.nodeName );
  3809. const uniformName = builder.getPropertyName( nodeUniform );
  3810. if ( builder.context.nodeName !== undefined ) delete builder.context.nodeName;
  3811. //
  3812. let snippet = uniformName;
  3813. if ( type === 'bool' ) {
  3814. // cache to variable
  3815. const nodeData = builder.getDataFromNode( this );
  3816. let propertyName = nodeData.propertyName;
  3817. if ( propertyName === undefined ) {
  3818. const nodeVar = builder.getVarFromNode( this, null, 'bool' );
  3819. propertyName = builder.getPropertyName( nodeVar );
  3820. nodeData.propertyName = propertyName;
  3821. snippet = builder.format( uniformName, sharedNodeType, type );
  3822. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  3823. }
  3824. snippet = propertyName;
  3825. }
  3826. return builder.format( snippet, type, output );
  3827. }
  3828. }
  3829. /**
  3830. * TSL function for creating a uniform node.
  3831. *
  3832. * @tsl
  3833. * @function
  3834. * @param {any|string} value - The value of this uniform or your type. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3835. * @param {string} [type] - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3836. * @returns {UniformNode}
  3837. */
  3838. const uniform = ( value, type ) => {
  3839. const nodeType = getConstNodeType( type || value );
  3840. if ( nodeType === value ) {
  3841. // if the value is a type but no having a value
  3842. value = getValueFromType( nodeType );
  3843. }
  3844. if ( value && value.isNode === true ) {
  3845. let v = value.value;
  3846. value.traverse( n => {
  3847. if ( n.isConstNode === true ) {
  3848. v = n.value;
  3849. }
  3850. } );
  3851. value = v;
  3852. }
  3853. return new UniformNode( value, nodeType );
  3854. };
  3855. /**
  3856. * ArrayNode represents a collection of nodes, typically created using the {@link array} function.
  3857. * ```js
  3858. * const colors = array( [
  3859. * vec3( 1, 0, 0 ),
  3860. * vec3( 0, 1, 0 ),
  3861. * vec3( 0, 0, 1 )
  3862. * ] );
  3863. *
  3864. * const redColor = tintColors.element( 0 );
  3865. * ```
  3866. *
  3867. * @augments TempNode
  3868. */
  3869. class ArrayNode extends TempNode {
  3870. static get type() {
  3871. return 'ArrayNode';
  3872. }
  3873. /**
  3874. * Constructs a new array node.
  3875. *
  3876. * @param {?string} nodeType - The data type of the elements.
  3877. * @param {number} count - Size of the array.
  3878. * @param {?Array<Node>} [values=null] - Array default values.
  3879. */
  3880. constructor( nodeType, count, values = null ) {
  3881. super( nodeType );
  3882. /**
  3883. * Array size.
  3884. *
  3885. * @type {number}
  3886. */
  3887. this.count = count;
  3888. /**
  3889. * Array default values.
  3890. *
  3891. * @type {?Array<Node>}
  3892. */
  3893. this.values = values;
  3894. /**
  3895. * This flag can be used for type testing.
  3896. *
  3897. * @type {boolean}
  3898. * @readonly
  3899. * @default true
  3900. */
  3901. this.isArrayNode = true;
  3902. }
  3903. /**
  3904. * Returns the number of elements in the node array.
  3905. *
  3906. * @param {NodeBuilder} builder - The current node builder.
  3907. * @return {number} The number of elements in the node array.
  3908. */
  3909. getArrayCount( /*builder*/ ) {
  3910. return this.count;
  3911. }
  3912. /**
  3913. * Returns the node's type.
  3914. *
  3915. * @param {NodeBuilder} builder - The current node builder.
  3916. * @return {string} The type of the node.
  3917. */
  3918. generateNodeType( builder ) {
  3919. if ( this.nodeType === null ) {
  3920. return this.values[ 0 ].getNodeType( builder );
  3921. }
  3922. return this.nodeType;
  3923. }
  3924. /**
  3925. * Returns the node's type.
  3926. *
  3927. * @param {NodeBuilder} builder - The current node builder.
  3928. * @return {string} The type of the node.
  3929. */
  3930. getElementType( builder ) {
  3931. return this.getNodeType( builder );
  3932. }
  3933. /**
  3934. * Returns the type of a member variable.
  3935. *
  3936. * @param {NodeBuilder} builder - The current node builder.
  3937. * @param {string} name - The name of the member variable.
  3938. * @return {string} The type of the member variable.
  3939. */
  3940. getMemberType( builder, name ) {
  3941. if ( this.nodeType === null ) {
  3942. return this.values[ 0 ].getMemberType( builder, name );
  3943. }
  3944. return super.getMemberType( builder, name );
  3945. }
  3946. /**
  3947. * This method builds the output node and returns the resulting array as a shader string.
  3948. *
  3949. * @param {NodeBuilder} builder - The current node builder.
  3950. * @return {string} The generated shader string.
  3951. */
  3952. generate( builder ) {
  3953. const type = this.getNodeType( builder );
  3954. return builder.generateArray( type, this.count, this.values );
  3955. }
  3956. }
  3957. /**
  3958. * TSL function for creating an array node.
  3959. *
  3960. * @tsl
  3961. * @function
  3962. * @param {string|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  3963. * or an array containing the default values (e.g., [ vec3() ]).
  3964. * @param {?number} [count] - Size of the array.
  3965. * @returns {ArrayNode}
  3966. */
  3967. const array = ( ...params ) => {
  3968. let node;
  3969. if ( params.length === 1 ) {
  3970. const values = params[ 0 ].map( ( value ) => nodeObject( value ) );
  3971. node = new ArrayNode( null, values.length, values );
  3972. } else {
  3973. const nodeType = params[ 0 ];
  3974. const count = params[ 1 ];
  3975. node = new ArrayNode( nodeType, count );
  3976. }
  3977. return node;
  3978. };
  3979. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
  3980. /**
  3981. * These node represents an assign operation. Meaning a node is assigned
  3982. * to another node.
  3983. *
  3984. * @augments TempNode
  3985. */
  3986. class AssignNode extends TempNode {
  3987. static get type() {
  3988. return 'AssignNode';
  3989. }
  3990. /**
  3991. * Constructs a new assign node.
  3992. *
  3993. * @param {Node} targetNode - The target node.
  3994. * @param {Node} sourceNode - The source type.
  3995. */
  3996. constructor( targetNode, sourceNode ) {
  3997. super();
  3998. /**
  3999. * The target node.
  4000. *
  4001. * @type {Node}
  4002. */
  4003. this.targetNode = targetNode;
  4004. /**
  4005. * The source node.
  4006. *
  4007. * @type {Node}
  4008. */
  4009. this.sourceNode = sourceNode;
  4010. /**
  4011. * This flag can be used for type testing.
  4012. *
  4013. * @type {boolean}
  4014. * @readonly
  4015. * @default true
  4016. */
  4017. this.isAssignNode = true;
  4018. }
  4019. /**
  4020. * Whether this node is used more than once in context of other nodes. This method
  4021. * is overwritten since it always returns `false` (assigns are unique).
  4022. *
  4023. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  4024. */
  4025. hasDependencies() {
  4026. return false;
  4027. }
  4028. generateNodeType( builder, output ) {
  4029. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  4030. }
  4031. /**
  4032. * Whether a split is required when assigning source to target. This can happen when the component length of
  4033. * target and source data type does not match.
  4034. *
  4035. * @param {NodeBuilder} builder - The current node builder.
  4036. * @return {boolean} Whether a split is required when assigning source to target.
  4037. */
  4038. needsSplitAssign( builder ) {
  4039. const { targetNode } = this;
  4040. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  4041. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  4042. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  4043. return assignDifferentVector;
  4044. }
  4045. return false;
  4046. }
  4047. setup( builder ) {
  4048. const { targetNode, sourceNode } = this;
  4049. const scope = targetNode.getScope();
  4050. const scopeData = builder.getDataFromNode( scope );
  4051. scopeData.assign = true;
  4052. const properties = builder.getNodeProperties( this );
  4053. properties.sourceNode = sourceNode;
  4054. properties.targetNode = targetNode.context( { assign: true } );
  4055. }
  4056. generate( builder, output ) {
  4057. const { targetNode, sourceNode } = builder.getNodeProperties( this );
  4058. const needsSplitAssign = this.needsSplitAssign( builder );
  4059. const target = targetNode.build( builder );
  4060. const targetType = targetNode.getNodeType( builder );
  4061. const source = sourceNode.build( builder, targetType );
  4062. const sourceType = sourceNode.getNodeType( builder );
  4063. const nodeData = builder.getDataFromNode( this );
  4064. //
  4065. let snippet;
  4066. if ( nodeData.initialized === true ) {
  4067. if ( output !== 'void' ) {
  4068. snippet = target;
  4069. }
  4070. } else if ( needsSplitAssign ) {
  4071. const sourceVar = builder.getVarFromNode( this, null, targetType );
  4072. const sourceProperty = builder.getPropertyName( sourceVar );
  4073. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  4074. const splitNode = targetNode.node;
  4075. const splitTargetNode = splitNode.node.context( { assign: true } );
  4076. const targetRoot = splitTargetNode.build( builder );
  4077. for ( let i = 0; i < splitNode.components.length; i ++ ) {
  4078. const component = splitNode.components[ i ];
  4079. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  4080. }
  4081. if ( output !== 'void' ) {
  4082. snippet = target;
  4083. }
  4084. } else {
  4085. snippet = `${ target } = ${ source }`;
  4086. if ( output === 'void' || sourceType === 'void' ) {
  4087. builder.addLineFlowCode( snippet, this );
  4088. if ( output !== 'void' ) {
  4089. snippet = target;
  4090. }
  4091. }
  4092. }
  4093. nodeData.initialized = true;
  4094. return builder.format( snippet, targetType, output );
  4095. }
  4096. }
  4097. /**
  4098. * TSL function for creating an assign node.
  4099. *
  4100. * @tsl
  4101. * @function
  4102. * @param {Node} targetNode - The target node.
  4103. * @param {Node} sourceNode - The source type.
  4104. * @returns {AssignNode}
  4105. */
  4106. const assign = /*@__PURE__*/ nodeProxy( AssignNode ).setParameterLength( 2 );
  4107. addMethodChaining( 'assign', assign );
  4108. /**
  4109. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  4110. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  4111. * this logic.
  4112. *
  4113. * @augments TempNode
  4114. */
  4115. class FunctionCallNode extends TempNode {
  4116. static get type() {
  4117. return 'FunctionCallNode';
  4118. }
  4119. /**
  4120. * Constructs a new function call node.
  4121. *
  4122. * @param {?FunctionNode} functionNode - The function node.
  4123. * @param {Object<string, Node>} [parameters={}] - The parameters for the function call.
  4124. */
  4125. constructor( functionNode = null, parameters = {} ) {
  4126. super();
  4127. /**
  4128. * The function node.
  4129. *
  4130. * @type {?FunctionNode}
  4131. * @default null
  4132. */
  4133. this.functionNode = functionNode;
  4134. /**
  4135. * The parameters of the function call.
  4136. *
  4137. * @type {Object<string, Node>}
  4138. * @default {}
  4139. */
  4140. this.parameters = parameters;
  4141. }
  4142. /**
  4143. * Sets the parameters of the function call node.
  4144. *
  4145. * @param {Object<string, Node>} parameters - The parameters to set.
  4146. * @return {FunctionCallNode} A reference to this node.
  4147. */
  4148. setParameters( parameters ) {
  4149. this.parameters = parameters;
  4150. return this;
  4151. }
  4152. /**
  4153. * Returns the parameters of the function call node.
  4154. *
  4155. * @return {Object<string, Node>} The parameters of this node.
  4156. */
  4157. getParameters() {
  4158. return this.parameters;
  4159. }
  4160. /**
  4161. * Returns the type of this function call node.
  4162. *
  4163. * @param {NodeBuilder} builder - The current node builder.
  4164. * @returns {string} The type of this node.
  4165. */
  4166. generateNodeType( builder ) {
  4167. return this.functionNode.getNodeType( builder );
  4168. }
  4169. /**
  4170. * Returns the function node of this function call node.
  4171. *
  4172. * @param {NodeBuilder} builder - The current node builder.
  4173. * @param {string} [name] - The name of the member.
  4174. * @returns {string} The type of the member.
  4175. */
  4176. getMemberType( builder, name ) {
  4177. return this.functionNode.getMemberType( builder, name );
  4178. }
  4179. generate( builder ) {
  4180. const params = [];
  4181. const functionNode = this.functionNode;
  4182. const inputs = functionNode.getInputs( builder );
  4183. const parameters = this.parameters;
  4184. const generateInput = ( node, inputNode ) => {
  4185. const type = inputNode.type;
  4186. const pointer = type === 'pointer';
  4187. let output;
  4188. if ( pointer ) output = '&' + node.build( builder );
  4189. else output = node.build( builder, type );
  4190. return output;
  4191. };
  4192. if ( Array.isArray( parameters ) ) {
  4193. if ( parameters.length > inputs.length ) {
  4194. error( 'TSL: The number of provided parameters exceeds the expected number of inputs in \'Fn()\'.' );
  4195. parameters.length = inputs.length;
  4196. } else if ( parameters.length < inputs.length ) {
  4197. error( 'TSL: The number of provided parameters is less than the expected number of inputs in \'Fn()\'.' );
  4198. while ( parameters.length < inputs.length ) {
  4199. parameters.push( float( 0 ) );
  4200. }
  4201. }
  4202. for ( let i = 0; i < parameters.length; i ++ ) {
  4203. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  4204. }
  4205. } else {
  4206. for ( const inputNode of inputs ) {
  4207. const node = parameters[ inputNode.name ];
  4208. if ( node !== undefined ) {
  4209. params.push( generateInput( node, inputNode ) );
  4210. } else {
  4211. error( `TSL: Input '${ inputNode.name }' not found in \'Fn()\'.` );
  4212. params.push( generateInput( float( 0 ), inputNode ) );
  4213. }
  4214. }
  4215. }
  4216. const functionName = functionNode.build( builder, 'property' );
  4217. return `${ functionName }( ${ params.join( ', ' ) } )`;
  4218. }
  4219. }
  4220. const call = ( func, ...params ) => {
  4221. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  4222. return new FunctionCallNode( nodeObject( func ), params );
  4223. };
  4224. addMethodChaining( 'call', call );
  4225. const _vectorOperators = {
  4226. '==': 'equal',
  4227. '!=': 'notEqual',
  4228. '<': 'lessThan',
  4229. '>': 'greaterThan',
  4230. '<=': 'lessThanEqual',
  4231. '>=': 'greaterThanEqual',
  4232. '%': 'mod'
  4233. };
  4234. /**
  4235. * This node represents basic mathematical and logical operations like addition,
  4236. * subtraction or comparisons (e.g. `equal()`).
  4237. *
  4238. * @augments TempNode
  4239. */
  4240. class OperatorNode extends TempNode {
  4241. static get type() {
  4242. return 'OperatorNode';
  4243. }
  4244. /**
  4245. * Constructs a new operator node.
  4246. *
  4247. * @param {string} op - The operator.
  4248. * @param {Node} aNode - The first input.
  4249. * @param {Node} bNode - The second input.
  4250. * @param {...Node} params - Additional input parameters.
  4251. */
  4252. constructor( op, aNode, bNode, ...params ) {
  4253. super();
  4254. if ( params.length > 0 ) {
  4255. let finalOp = new OperatorNode( op, aNode, bNode );
  4256. for ( let i = 0; i < params.length - 1; i ++ ) {
  4257. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  4258. }
  4259. aNode = finalOp;
  4260. bNode = params[ params.length - 1 ];
  4261. }
  4262. /**
  4263. * The operator.
  4264. *
  4265. * @type {string}
  4266. */
  4267. this.op = op;
  4268. /**
  4269. * The first input.
  4270. *
  4271. * @type {Node}
  4272. */
  4273. this.aNode = aNode;
  4274. /**
  4275. * The second input.
  4276. *
  4277. * @type {Node}
  4278. */
  4279. this.bNode = bNode;
  4280. /**
  4281. * This flag can be used for type testing.
  4282. *
  4283. * @type {boolean}
  4284. * @readonly
  4285. * @default true
  4286. */
  4287. this.isOperatorNode = true;
  4288. }
  4289. /**
  4290. * Returns the operator method name.
  4291. *
  4292. * @param {NodeBuilder} builder - The current node builder.
  4293. * @param {string} output - The output type.
  4294. * @returns {string} The operator method name.
  4295. */
  4296. getOperatorMethod( builder, output ) {
  4297. return builder.getMethod( _vectorOperators[ this.op ], output );
  4298. }
  4299. /**
  4300. * This method is overwritten since the node type is inferred from the operator
  4301. * and the input node types.
  4302. *
  4303. * @param {NodeBuilder} builder - The current node builder.
  4304. * @param {?string} [output=null] - The output type.
  4305. * @return {string} The node type.
  4306. */
  4307. generateNodeType( builder, output = null ) {
  4308. const op = this.op;
  4309. const aNode = this.aNode;
  4310. const bNode = this.bNode;
  4311. const typeA = aNode.getNodeType( builder );
  4312. const typeB = bNode ? bNode.getNodeType( builder ) : null;
  4313. if ( typeA === 'void' || typeB === 'void' ) {
  4314. return output || 'void';
  4315. } else if ( op === '%' ) {
  4316. return typeA;
  4317. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  4318. return builder.getIntegerType( typeA );
  4319. } else if ( op === '&&' || op === '||' || op === '^^' ) {
  4320. return 'bool';
  4321. } else if ( op === '!' ) {
  4322. const typeLength = builder.getTypeLength( typeA );
  4323. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  4324. } else if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  4325. const typeLength = Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  4326. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  4327. } else {
  4328. // Handle matrix operations
  4329. if ( builder.isMatrix( typeA ) ) {
  4330. if ( typeB === 'float' ) {
  4331. return typeA; // matrix * scalar = matrix
  4332. } else if ( builder.isVector( typeB ) ) {
  4333. return builder.getVectorFromMatrix( typeA ); // matrix * vector
  4334. } else if ( builder.isMatrix( typeB ) ) {
  4335. return typeA; // matrix * matrix
  4336. }
  4337. } else if ( builder.isMatrix( typeB ) ) {
  4338. if ( typeA === 'float' ) {
  4339. return typeB; // scalar * matrix = matrix
  4340. } else if ( builder.isVector( typeA ) ) {
  4341. return builder.getVectorFromMatrix( typeB ); // vector * matrix
  4342. }
  4343. }
  4344. // Handle non-matrix cases
  4345. if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  4346. // anytype x anytype: use the greater length vector
  4347. return typeB;
  4348. }
  4349. return typeA;
  4350. }
  4351. }
  4352. generate( builder, output ) {
  4353. const op = this.op;
  4354. const { aNode, bNode } = this;
  4355. const type = this.getNodeType( builder, output );
  4356. let typeA = null;
  4357. let typeB = null;
  4358. if ( type !== 'void' ) {
  4359. typeA = aNode.getNodeType( builder );
  4360. typeB = bNode ? bNode.getNodeType( builder ) : null;
  4361. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' || op === '!=' ) {
  4362. if ( builder.isVector( typeA ) ) {
  4363. typeB = typeA;
  4364. } else if ( builder.isVector( typeB ) ) {
  4365. typeA = typeB;
  4366. } else if ( typeA !== typeB ) {
  4367. typeA = typeB = 'float';
  4368. }
  4369. } else if ( op === '>>' || op === '<<' ) {
  4370. typeA = type;
  4371. typeB = builder.changeComponentType( typeB, 'uint' );
  4372. } else if ( op === '%' ) {
  4373. typeA = type;
  4374. typeB = builder.isInteger( typeA ) && builder.isInteger( typeB ) ? typeB : typeA;
  4375. } else if ( builder.isMatrix( typeA ) ) {
  4376. if ( typeB === 'float' ) {
  4377. // Keep matrix type for typeA, but ensure typeB stays float
  4378. typeB = 'float';
  4379. } else if ( builder.isVector( typeB ) ) {
  4380. // matrix x vector
  4381. typeB = builder.getVectorFromMatrix( typeA );
  4382. } else if ( builder.isMatrix( typeB ) ) ; else {
  4383. typeA = typeB = type;
  4384. }
  4385. } else if ( builder.isMatrix( typeB ) ) {
  4386. if ( typeA === 'float' ) {
  4387. // Keep matrix type for typeB, but ensure typeA stays float
  4388. typeA = 'float';
  4389. } else if ( builder.isVector( typeA ) ) {
  4390. // vector x matrix
  4391. typeA = builder.getVectorFromMatrix( typeB );
  4392. } else {
  4393. typeA = typeB = type;
  4394. }
  4395. } else {
  4396. // anytype x anytype
  4397. typeA = typeB = type;
  4398. }
  4399. } else {
  4400. typeA = typeB = type;
  4401. }
  4402. const a = aNode.build( builder, typeA );
  4403. const b = bNode ? bNode.build( builder, typeB ) : null;
  4404. const fnOpSnippet = builder.getFunctionOperator( op );
  4405. if ( output !== 'void' ) {
  4406. const isGLSL = builder.renderer.coordinateSystem === WebGLCoordinateSystem;
  4407. if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  4408. if ( isGLSL ) {
  4409. if ( builder.isVector( typeA ) ) {
  4410. return builder.format( `${ this.getOperatorMethod( builder, output ) }( ${ a }, ${ b } )`, type, output );
  4411. } else {
  4412. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  4413. }
  4414. } else {
  4415. // WGSL
  4416. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  4417. }
  4418. } else if ( op === '%' ) {
  4419. if ( builder.isInteger( typeB ) ) {
  4420. return builder.format( `( ${ a } % ${ b } )`, type, output );
  4421. } else {
  4422. return builder.format( `${ this.getOperatorMethod( builder, type ) }( ${ a }, ${ b } )`, type, output );
  4423. }
  4424. } else if ( op === '!' ) {
  4425. if ( isGLSL && builder.isVector( typeA ) ) {
  4426. return builder.format( `not( ${a} )`, output );
  4427. } else {
  4428. // WGSL and scalars on GLSL
  4429. return builder.format( `( ${op} ${a} )`, typeA, output );
  4430. }
  4431. } else if ( op === '~' ) {
  4432. return builder.format( `( ${op} ${a} )`, typeA, output );
  4433. } else if ( fnOpSnippet ) {
  4434. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  4435. } else {
  4436. // Handle matrix operations
  4437. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  4438. return builder.format( `( ${ b } ${ op } ${ a } )`, type, output );
  4439. } else if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  4440. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  4441. } else {
  4442. let snippet = `( ${ a } ${ op } ${ b } )`;
  4443. if ( ! isGLSL && type === 'bool' && builder.isVector( typeA ) && builder.isVector( typeB ) ) {
  4444. snippet = `all${ snippet }`;
  4445. }
  4446. return builder.format( snippet, type, output );
  4447. }
  4448. }
  4449. } else if ( typeA !== 'void' ) {
  4450. if ( fnOpSnippet ) {
  4451. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  4452. } else {
  4453. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  4454. return builder.format( `${ b } ${ op } ${ a }`, type, output );
  4455. } else {
  4456. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  4457. }
  4458. }
  4459. }
  4460. }
  4461. serialize( data ) {
  4462. super.serialize( data );
  4463. data.op = this.op;
  4464. }
  4465. deserialize( data ) {
  4466. super.deserialize( data );
  4467. this.op = data.op;
  4468. }
  4469. }
  4470. /**
  4471. * Returns the addition of two or more value.
  4472. *
  4473. * @tsl
  4474. * @function
  4475. * @param {Node} a - The first input.
  4476. * @param {Node} b - The second input.
  4477. * @param {...Node} params - Additional input parameters.
  4478. * @returns {OperatorNode}
  4479. */
  4480. const add = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '+' ).setParameterLength( 2, Infinity ).setName( 'add' );
  4481. /**
  4482. * Returns the subtraction of two or more value.
  4483. *
  4484. * @tsl
  4485. * @function
  4486. * @param {Node} a - The first input.
  4487. * @param {Node} b - The second input.
  4488. * @param {...Node} params - Additional input parameters.
  4489. * @returns {OperatorNode}
  4490. */
  4491. const sub = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '-' ).setParameterLength( 2, Infinity ).setName( 'sub' );
  4492. /**
  4493. * Returns the multiplication of two or more value.
  4494. *
  4495. * @tsl
  4496. * @function
  4497. * @param {Node} a - The first input.
  4498. * @param {Node} b - The second input.
  4499. * @param {...Node} params - Additional input parameters.
  4500. * @returns {OperatorNode}
  4501. */
  4502. const mul = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '*' ).setParameterLength( 2, Infinity ).setName( 'mul' );
  4503. /**
  4504. * Returns the division of two or more value.
  4505. *
  4506. * @tsl
  4507. * @function
  4508. * @param {Node} a - The first input.
  4509. * @param {Node} b - The second input.
  4510. * @param {...Node} params - Additional input parameters.
  4511. * @returns {OperatorNode}
  4512. */
  4513. const div = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '/' ).setParameterLength( 2, Infinity ).setName( 'div' );
  4514. /**
  4515. * Computes the remainder of dividing the first node by the second one.
  4516. *
  4517. * @tsl
  4518. * @function
  4519. * @param {Node} a - The first input.
  4520. * @param {Node} b - The second input.
  4521. * @returns {OperatorNode}
  4522. */
  4523. const mod = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '%' ).setParameterLength( 2 ).setName( 'mod' );
  4524. /**
  4525. * Checks if two nodes are equal.
  4526. *
  4527. * @tsl
  4528. * @function
  4529. * @param {Node} a - The first input.
  4530. * @param {Node} b - The second input.
  4531. * @returns {OperatorNode}
  4532. */
  4533. const equal = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '==' ).setParameterLength( 2 ).setName( 'equal' );
  4534. /**
  4535. * Checks if two nodes are not equal.
  4536. *
  4537. * @tsl
  4538. * @function
  4539. * @param {Node} a - The first input.
  4540. * @param {Node} b - The second input.
  4541. * @returns {OperatorNode}
  4542. */
  4543. const notEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!=' ).setParameterLength( 2 ).setName( 'notEqual' );
  4544. /**
  4545. * Checks if the first node is less than the second.
  4546. *
  4547. * @tsl
  4548. * @function
  4549. * @param {Node} a - The first input.
  4550. * @param {Node} b - The second input.
  4551. * @returns {OperatorNode}
  4552. */
  4553. const lessThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<' ).setParameterLength( 2 ).setName( 'lessThan' );
  4554. /**
  4555. * Checks if the first node is greater than the second.
  4556. *
  4557. * @tsl
  4558. * @function
  4559. * @param {Node} a - The first input.
  4560. * @param {Node} b - The second input.
  4561. * @returns {OperatorNode}
  4562. */
  4563. const greaterThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>' ).setParameterLength( 2 ).setName( 'greaterThan' );
  4564. /**
  4565. * Checks if the first node is less than or equal to the second.
  4566. *
  4567. * @tsl
  4568. * @function
  4569. * @param {Node} a - The first input.
  4570. * @param {Node} b - The second input.
  4571. * @returns {OperatorNode}
  4572. */
  4573. const lessThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<=' ).setParameterLength( 2 ).setName( 'lessThanEqual' );
  4574. /**
  4575. * Checks if the first node is greater than or equal to the second.
  4576. *
  4577. * @tsl
  4578. * @function
  4579. * @param {Node} a - The first input.
  4580. * @param {Node} b - The second input.
  4581. * @returns {OperatorNode}
  4582. */
  4583. const greaterThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>=' ).setParameterLength( 2 ).setName( 'greaterThanEqual' );
  4584. /**
  4585. * Performs a logical AND operation on multiple nodes.
  4586. *
  4587. * @tsl
  4588. * @function
  4589. * @param {...Node} nodes - The input nodes to be combined using AND.
  4590. * @returns {OperatorNode}
  4591. */
  4592. const and = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&&' ).setParameterLength( 2, Infinity ).setName( 'and' );
  4593. /**
  4594. * Performs a logical OR operation on multiple nodes.
  4595. *
  4596. * @tsl
  4597. * @function
  4598. * @param {...Node} nodes - The input nodes to be combined using OR.
  4599. * @returns {OperatorNode}
  4600. */
  4601. const or = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '||' ).setParameterLength( 2, Infinity ).setName( 'or' );
  4602. /**
  4603. * Performs logical NOT on a node.
  4604. *
  4605. * @tsl
  4606. * @function
  4607. * @param {Node} value - The value.
  4608. * @returns {OperatorNode}
  4609. */
  4610. const not = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!' ).setParameterLength( 1 ).setName( 'not' );
  4611. /**
  4612. * Performs logical XOR on two nodes.
  4613. *
  4614. * @tsl
  4615. * @function
  4616. * @param {Node} a - The first input.
  4617. * @param {Node} b - The second input.
  4618. * @returns {OperatorNode}
  4619. */
  4620. const xor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^^' ).setParameterLength( 2 ).setName( 'xor' );
  4621. /**
  4622. * Performs bitwise AND on two nodes.
  4623. *
  4624. * @tsl
  4625. * @function
  4626. * @param {Node} a - The first input.
  4627. * @param {Node} b - The second input.
  4628. * @returns {OperatorNode}
  4629. */
  4630. const bitAnd = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&' ).setParameterLength( 2 ).setName( 'bitAnd' );
  4631. /**
  4632. * Performs bitwise NOT on a node.
  4633. *
  4634. * @tsl
  4635. * @function
  4636. * @param {Node} a - The first input.
  4637. * @param {Node} b - The second input.
  4638. * @returns {OperatorNode}
  4639. */
  4640. const bitNot = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '~' ).setParameterLength( 1 ).setName( 'bitNot' );
  4641. /**
  4642. * Performs bitwise OR on two nodes.
  4643. *
  4644. * @tsl
  4645. * @function
  4646. * @param {Node} a - The first input.
  4647. * @param {Node} b - The second input.
  4648. * @returns {OperatorNode}
  4649. */
  4650. const bitOr = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '|' ).setParameterLength( 2 ).setName( 'bitOr' );
  4651. /**
  4652. * Performs bitwise XOR on two nodes.
  4653. *
  4654. * @tsl
  4655. * @function
  4656. * @param {Node} a - The first input.
  4657. * @param {Node} b - The second input.
  4658. * @returns {OperatorNode}
  4659. */
  4660. const bitXor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^' ).setParameterLength( 2 ).setName( 'bitXor' );
  4661. /**
  4662. * Shifts a node to the left.
  4663. *
  4664. * @tsl
  4665. * @function
  4666. * @param {Node} a - The node to shift.
  4667. * @param {Node} b - The value to shift.
  4668. * @returns {OperatorNode}
  4669. */
  4670. const shiftLeft = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<<' ).setParameterLength( 2 ).setName( 'shiftLeft' );
  4671. /**
  4672. * Shifts a node to the right.
  4673. *
  4674. * @tsl
  4675. * @function
  4676. * @param {Node} a - The node to shift.
  4677. * @param {Node} b - The value to shift.
  4678. * @returns {OperatorNode}
  4679. */
  4680. const shiftRight = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>>' ).setParameterLength( 2 ).setName( 'shiftRight' );
  4681. /**
  4682. * Increments a node by 1.
  4683. *
  4684. * @tsl
  4685. * @function
  4686. * @param {Node} a - The node to increment.
  4687. * @returns {OperatorNode}
  4688. */
  4689. const incrementBefore = Fn( ( [ a ] ) => {
  4690. a.addAssign( 1 );
  4691. return a;
  4692. } );
  4693. /**
  4694. * Decrements a node by 1.
  4695. *
  4696. * @tsl
  4697. * @function
  4698. * @param {Node} a - The node to decrement.
  4699. * @returns {OperatorNode}
  4700. */
  4701. const decrementBefore = Fn( ( [ a ] ) => {
  4702. a.subAssign( 1 );
  4703. return a;
  4704. } );
  4705. /**
  4706. * Increments a node by 1 and returns the previous value.
  4707. *
  4708. * @tsl
  4709. * @function
  4710. * @param {Node} a - The node to increment.
  4711. * @returns {OperatorNode}
  4712. */
  4713. const increment = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4714. const temp = int( a ).toConst();
  4715. a.addAssign( 1 );
  4716. return temp;
  4717. } );
  4718. /**
  4719. * Decrements a node by 1 and returns the previous value.
  4720. *
  4721. * @tsl
  4722. * @function
  4723. * @param {Node} a - The node to decrement.
  4724. * @returns {OperatorNode}
  4725. */
  4726. const decrement = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4727. const temp = int( a ).toConst();
  4728. a.subAssign( 1 );
  4729. return temp;
  4730. } );
  4731. addMethodChaining( 'add', add );
  4732. addMethodChaining( 'sub', sub );
  4733. addMethodChaining( 'mul', mul );
  4734. addMethodChaining( 'div', div );
  4735. addMethodChaining( 'mod', mod );
  4736. addMethodChaining( 'equal', equal );
  4737. addMethodChaining( 'notEqual', notEqual );
  4738. addMethodChaining( 'lessThan', lessThan );
  4739. addMethodChaining( 'greaterThan', greaterThan );
  4740. addMethodChaining( 'lessThanEqual', lessThanEqual );
  4741. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  4742. addMethodChaining( 'and', and );
  4743. addMethodChaining( 'or', or );
  4744. addMethodChaining( 'not', not );
  4745. addMethodChaining( 'xor', xor );
  4746. addMethodChaining( 'bitAnd', bitAnd );
  4747. addMethodChaining( 'bitNot', bitNot );
  4748. addMethodChaining( 'bitOr', bitOr );
  4749. addMethodChaining( 'bitXor', bitXor );
  4750. addMethodChaining( 'shiftLeft', shiftLeft );
  4751. addMethodChaining( 'shiftRight', shiftRight );
  4752. addMethodChaining( 'incrementBefore', incrementBefore );
  4753. addMethodChaining( 'decrementBefore', decrementBefore );
  4754. addMethodChaining( 'increment', increment );
  4755. addMethodChaining( 'decrement', decrement );
  4756. /**
  4757. * This node represents a variety of mathematical methods available in shaders.
  4758. * They are divided into three categories:
  4759. *
  4760. * - Methods with one input like `sin`, `cos` or `normalize`.
  4761. * - Methods with two inputs like `dot`, `cross` or `pow`.
  4762. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  4763. *
  4764. * @augments TempNode
  4765. */
  4766. class MathNode extends TempNode {
  4767. static get type() {
  4768. return 'MathNode';
  4769. }
  4770. /**
  4771. * Constructs a new math node.
  4772. *
  4773. * @param {string} method - The method name.
  4774. * @param {Node} aNode - The first input.
  4775. * @param {?Node} [bNode=null] - The second input.
  4776. * @param {?Node} [cNode=null] - The third input.
  4777. */
  4778. constructor( method, aNode, bNode = null, cNode = null ) {
  4779. super();
  4780. // Allow the max() and min() functions to take an arbitrary number of arguments.
  4781. if ( ( method === MathNode.MAX || method === MathNode.MIN ) && arguments.length > 3 ) {
  4782. let finalOp = new MathNode( method, aNode, bNode );
  4783. for ( let i = 3; i < arguments.length - 1; i ++ ) {
  4784. finalOp = new MathNode( method, finalOp, arguments[ i ] );
  4785. }
  4786. aNode = finalOp;
  4787. bNode = arguments[ arguments.length - 1 ];
  4788. cNode = null;
  4789. }
  4790. /**
  4791. * The method name.
  4792. *
  4793. * @type {string}
  4794. */
  4795. this.method = method;
  4796. /**
  4797. * The first input.
  4798. *
  4799. * @type {Node}
  4800. */
  4801. this.aNode = aNode;
  4802. /**
  4803. * The second input.
  4804. *
  4805. * @type {?Node}
  4806. * @default null
  4807. */
  4808. this.bNode = bNode;
  4809. /**
  4810. * The third input.
  4811. *
  4812. * @type {?Node}
  4813. * @default null
  4814. */
  4815. this.cNode = cNode;
  4816. /**
  4817. * This flag can be used for type testing.
  4818. *
  4819. * @type {boolean}
  4820. * @readonly
  4821. * @default true
  4822. */
  4823. this.isMathNode = true;
  4824. }
  4825. /**
  4826. * The input type is inferred from the node types of the input nodes.
  4827. *
  4828. * @param {NodeBuilder} builder - The current node builder.
  4829. * @return {string} The input type.
  4830. */
  4831. getInputType( builder ) {
  4832. const aType = this.aNode.getNodeType( builder );
  4833. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  4834. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  4835. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  4836. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  4837. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  4838. if ( aLen > bLen && aLen > cLen ) {
  4839. return aType;
  4840. } else if ( bLen > cLen ) {
  4841. return bType;
  4842. } else if ( cLen > aLen ) {
  4843. return cType;
  4844. }
  4845. return aType;
  4846. }
  4847. /**
  4848. * The selected method as well as the input type determine the node type of this node.
  4849. *
  4850. * @param {NodeBuilder} builder - The current node builder.
  4851. * @return {string} The node type.
  4852. */
  4853. generateNodeType( builder ) {
  4854. const method = this.method;
  4855. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  4856. return 'float';
  4857. } else if ( method === MathNode.CROSS ) {
  4858. return 'vec3';
  4859. } else if ( method === MathNode.ALL || method === MathNode.ANY ) {
  4860. return 'bool';
  4861. } else if ( method === MathNode.EQUALS ) {
  4862. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  4863. } else {
  4864. return this.getInputType( builder );
  4865. }
  4866. }
  4867. setup( builder ) {
  4868. const { aNode, bNode, method } = this;
  4869. let outputNode = null;
  4870. if ( method === MathNode.ONE_MINUS ) {
  4871. outputNode = sub( 1.0, aNode );
  4872. } else if ( method === MathNode.RECIPROCAL ) {
  4873. outputNode = div( 1.0, aNode );
  4874. } else if ( method === MathNode.DIFFERENCE ) {
  4875. outputNode = abs( sub( aNode, bNode ) );
  4876. } else if ( method === MathNode.TRANSFORM_DIRECTION ) {
  4877. // pre-multiplies the direction by the matrix and normalizes the result
  4878. let matrixNode, directionNode;
  4879. if ( builder.isMatrix( aNode.getNodeType( builder ) ) ) {
  4880. matrixNode = aNode;
  4881. directionNode = bNode;
  4882. } else {
  4883. matrixNode = bNode;
  4884. directionNode = aNode;
  4885. }
  4886. outputNode = normalize( mul( matrixNode, vec4( vec3( directionNode ), 0.0 ) ).xyz );
  4887. }
  4888. if ( outputNode !== null ) {
  4889. return outputNode;
  4890. } else {
  4891. return super.setup( builder );
  4892. }
  4893. }
  4894. generate( builder, output ) {
  4895. const properties = builder.getNodeProperties( this );
  4896. if ( properties.outputNode ) {
  4897. return super.generate( builder, output );
  4898. }
  4899. let method = this.method;
  4900. const type = this.getNodeType( builder );
  4901. const inputType = this.getInputType( builder );
  4902. const a = this.aNode;
  4903. const b = this.bNode;
  4904. const c = this.cNode;
  4905. const coordinateSystem = builder.renderer.coordinateSystem;
  4906. if ( method === MathNode.NEGATE ) {
  4907. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  4908. } else {
  4909. const params = [];
  4910. if ( method === MathNode.CROSS ) {
  4911. params.push(
  4912. a.build( builder, type ),
  4913. b.build( builder, type )
  4914. );
  4915. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  4916. params.push(
  4917. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  4918. b.build( builder, inputType )
  4919. );
  4920. } else if ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) {
  4921. params.push(
  4922. a.build( builder, inputType ),
  4923. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4924. );
  4925. } else if ( method === MathNode.REFRACT ) {
  4926. params.push(
  4927. a.build( builder, inputType ),
  4928. b.build( builder, inputType ),
  4929. c.build( builder, 'float' )
  4930. );
  4931. } else if ( method === MathNode.MIX ) {
  4932. params.push(
  4933. a.build( builder, inputType ),
  4934. b.build( builder, inputType ),
  4935. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4936. );
  4937. } else {
  4938. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  4939. method = 'atan2';
  4940. }
  4941. if ( builder.shaderStage !== 'fragment' && ( method === MathNode.DFDX || method === MathNode.DFDY ) ) {
  4942. warn( `TSL: '${ method }' is not supported in the ${ builder.shaderStage } stage.`, this.stackTrace );
  4943. method = '/*' + method + '*/';
  4944. }
  4945. params.push( a.build( builder, inputType ) );
  4946. if ( b !== null ) params.push( b.build( builder, inputType ) );
  4947. if ( c !== null ) params.push( c.build( builder, inputType ) );
  4948. }
  4949. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  4950. }
  4951. }
  4952. serialize( data ) {
  4953. super.serialize( data );
  4954. data.method = this.method;
  4955. }
  4956. deserialize( data ) {
  4957. super.deserialize( data );
  4958. this.method = data.method;
  4959. }
  4960. }
  4961. // 1 input
  4962. MathNode.ALL = 'all';
  4963. MathNode.ANY = 'any';
  4964. MathNode.RADIANS = 'radians';
  4965. MathNode.DEGREES = 'degrees';
  4966. MathNode.EXP = 'exp';
  4967. MathNode.EXP2 = 'exp2';
  4968. MathNode.LOG = 'log';
  4969. MathNode.LOG2 = 'log2';
  4970. MathNode.SQRT = 'sqrt';
  4971. MathNode.INVERSE_SQRT = 'inversesqrt';
  4972. MathNode.FLOOR = 'floor';
  4973. MathNode.CEIL = 'ceil';
  4974. MathNode.NORMALIZE = 'normalize';
  4975. MathNode.FRACT = 'fract';
  4976. MathNode.SIN = 'sin';
  4977. MathNode.SINH = 'sinh';
  4978. MathNode.COS = 'cos';
  4979. MathNode.COSH = 'cosh';
  4980. MathNode.TAN = 'tan';
  4981. MathNode.TANH = 'tanh';
  4982. MathNode.ASIN = 'asin';
  4983. MathNode.ASINH = 'asinh';
  4984. MathNode.ACOS = 'acos';
  4985. MathNode.ACOSH = 'acosh';
  4986. MathNode.ATAN = 'atan';
  4987. MathNode.ATANH = 'atanh';
  4988. MathNode.ABS = 'abs';
  4989. MathNode.SIGN = 'sign';
  4990. MathNode.LENGTH = 'length';
  4991. MathNode.NEGATE = 'negate';
  4992. MathNode.ONE_MINUS = 'oneMinus';
  4993. MathNode.DFDX = 'dFdx';
  4994. MathNode.DFDY = 'dFdy';
  4995. MathNode.ROUND = 'round';
  4996. MathNode.RECIPROCAL = 'reciprocal';
  4997. MathNode.TRUNC = 'trunc';
  4998. MathNode.FWIDTH = 'fwidth';
  4999. MathNode.TRANSPOSE = 'transpose';
  5000. MathNode.DETERMINANT = 'determinant';
  5001. MathNode.INVERSE = 'inverse';
  5002. // 2 inputs
  5003. MathNode.EQUALS = 'equals';
  5004. MathNode.MIN = 'min';
  5005. MathNode.MAX = 'max';
  5006. MathNode.STEP = 'step';
  5007. MathNode.REFLECT = 'reflect';
  5008. MathNode.DISTANCE = 'distance';
  5009. MathNode.DIFFERENCE = 'difference';
  5010. MathNode.DOT = 'dot';
  5011. MathNode.CROSS = 'cross';
  5012. MathNode.POW = 'pow';
  5013. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  5014. // 3 inputs
  5015. MathNode.MIX = 'mix';
  5016. MathNode.CLAMP = 'clamp';
  5017. MathNode.REFRACT = 'refract';
  5018. MathNode.SMOOTHSTEP = 'smoothstep';
  5019. MathNode.FACEFORWARD = 'faceforward';
  5020. // 1 inputs
  5021. /**
  5022. * A small value used to handle floating-point precision errors.
  5023. *
  5024. * @tsl
  5025. * @type {Node<float>}
  5026. */
  5027. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  5028. /**
  5029. * Represents infinity.
  5030. *
  5031. * @tsl
  5032. * @type {Node<float>}
  5033. */
  5034. const INFINITY = /*@__PURE__*/ float( 1e6 );
  5035. /**
  5036. * Represents PI.
  5037. *
  5038. * @tsl
  5039. * @type {Node<float>}
  5040. */
  5041. const PI = /*@__PURE__*/ float( Math.PI );
  5042. /**
  5043. * Represents PI * 2. Please use the non-deprecated version `TWO_PI`.
  5044. *
  5045. * @tsl
  5046. * @deprecated
  5047. * @type {Node<float>}
  5048. */
  5049. const PI2 = /*@__PURE__*/ float( Math.PI * 2 ); // @deprecated r181
  5050. /**
  5051. * Represents PI * 2.
  5052. *
  5053. * @tsl
  5054. * @type {Node<float>}
  5055. */
  5056. const TWO_PI = /*@__PURE__*/ float( Math.PI * 2 );
  5057. /**
  5058. * Represents PI / 2.
  5059. *
  5060. * @tsl
  5061. * @type {Node<float>}
  5062. */
  5063. const HALF_PI = /*@__PURE__*/ float( Math.PI * 0.5 );
  5064. /**
  5065. * Returns `true` if all components of `x` are `true`.
  5066. *
  5067. * @tsl
  5068. * @function
  5069. * @param {Node | number} x - The parameter.
  5070. * @returns {Node<bool>}
  5071. */
  5072. const all = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ALL ).setParameterLength( 1 );
  5073. /**
  5074. * Returns `true` if any components of `x` are `true`.
  5075. *
  5076. * @tsl
  5077. * @function
  5078. * @param {Node | number} x - The parameter.
  5079. * @returns {Node<bool>}
  5080. */
  5081. const any = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ANY ).setParameterLength( 1 );
  5082. /**
  5083. * Converts a quantity in degrees to radians.
  5084. *
  5085. * @tsl
  5086. * @function
  5087. * @param {Node | number} x - The input in degrees.
  5088. * @returns {Node}
  5089. */
  5090. const radians = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RADIANS ).setParameterLength( 1 );
  5091. /**
  5092. * Convert a quantity in radians to degrees.
  5093. *
  5094. * @tsl
  5095. * @function
  5096. * @param {Node | number} x - The input in radians.
  5097. * @returns {Node}
  5098. */
  5099. const degrees = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DEGREES ).setParameterLength( 1 );
  5100. /**
  5101. * Returns the natural exponentiation of the parameter.
  5102. *
  5103. * @tsl
  5104. * @function
  5105. * @param {Node | number} x - The parameter.
  5106. * @returns {Node}
  5107. */
  5108. const exp = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP ).setParameterLength( 1 );
  5109. /**
  5110. * Returns 2 raised to the power of the parameter.
  5111. *
  5112. * @tsl
  5113. * @function
  5114. * @param {Node | number} x - The parameter.
  5115. * @returns {Node}
  5116. */
  5117. const exp2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP2 ).setParameterLength( 1 );
  5118. /**
  5119. * Returns the natural logarithm of the parameter.
  5120. *
  5121. * @tsl
  5122. * @function
  5123. * @param {Node | number} x - The parameter.
  5124. * @returns {Node}
  5125. */
  5126. const log = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG ).setParameterLength( 1 );
  5127. /**
  5128. * Returns the base 2 logarithm of the parameter.
  5129. *
  5130. * @tsl
  5131. * @function
  5132. * @param {Node | number} x - The parameter.
  5133. * @returns {Node}
  5134. */
  5135. const log2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG2 ).setParameterLength( 1 );
  5136. /**
  5137. * Returns the square root of the parameter.
  5138. *
  5139. * @tsl
  5140. * @function
  5141. * @param {Node | number} x - The parameter.
  5142. * @returns {Node}
  5143. */
  5144. const sqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SQRT ).setParameterLength( 1 );
  5145. /**
  5146. * Returns the inverse of the square root of the parameter.
  5147. *
  5148. * @tsl
  5149. * @function
  5150. * @param {Node | number} x - The parameter.
  5151. * @returns {Node}
  5152. */
  5153. const inverseSqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE_SQRT ).setParameterLength( 1 );
  5154. /**
  5155. * Finds the nearest integer less than or equal to the parameter.
  5156. *
  5157. * @tsl
  5158. * @function
  5159. * @param {Node | number} x - The parameter.
  5160. * @returns {Node}
  5161. */
  5162. const floor = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FLOOR ).setParameterLength( 1 );
  5163. /**
  5164. * Finds the nearest integer that is greater than or equal to the parameter.
  5165. *
  5166. * @tsl
  5167. * @function
  5168. * @param {Node | number} x - The parameter.
  5169. * @returns {Node}
  5170. */
  5171. const ceil = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CEIL ).setParameterLength( 1 );
  5172. /**
  5173. * Calculates the unit vector in the same direction as the original vector.
  5174. *
  5175. * @tsl
  5176. * @function
  5177. * @param {Node} x - The input vector.
  5178. * @returns {Node}
  5179. */
  5180. const normalize = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NORMALIZE ).setParameterLength( 1 );
  5181. /**
  5182. * Computes the fractional part of the parameter.
  5183. *
  5184. * @tsl
  5185. * @function
  5186. * @param {Node | number} x - The parameter.
  5187. * @returns {Node}
  5188. */
  5189. const fract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FRACT ).setParameterLength( 1 );
  5190. /**
  5191. * Returns the sine of the parameter.
  5192. *
  5193. * @tsl
  5194. * @function
  5195. * @param {Node | number} x - The parameter.
  5196. * @returns {Node}
  5197. */
  5198. const sin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIN ).setParameterLength( 1 );
  5199. /**
  5200. * Returns the hyperbolic sine of the parameter.
  5201. *
  5202. * @tsl
  5203. * @function
  5204. * @param {Node | number} x - The parameter.
  5205. * @returns {Node}
  5206. */
  5207. const sinh = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SINH ).setParameterLength( 1 );
  5208. /**
  5209. * Returns the cosine of the parameter.
  5210. *
  5211. * @tsl
  5212. * @function
  5213. * @param {Node | number} x - The parameter.
  5214. * @returns {Node}
  5215. */
  5216. const cos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.COS ).setParameterLength( 1 );
  5217. /**
  5218. * Returns the hyperbolic cosine of the parameter.
  5219. *
  5220. * @tsl
  5221. * @function
  5222. * @param {Node | number} x - The parameter.
  5223. * @returns {Node}
  5224. */
  5225. const cosh = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.COSH ).setParameterLength( 1 );
  5226. /**
  5227. * Returns the tangent of the parameter.
  5228. *
  5229. * @tsl
  5230. * @function
  5231. * @param {Node | number} x - The parameter.
  5232. * @returns {Node}
  5233. */
  5234. const tan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TAN ).setParameterLength( 1 );
  5235. /**
  5236. * Returns the hyperbolic tangent of the parameter.
  5237. *
  5238. * @tsl
  5239. * @function
  5240. * @param {Node | number} x - The parameter.
  5241. * @returns {Node}
  5242. */
  5243. const tanh = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TANH ).setParameterLength( 1 );
  5244. /**
  5245. * Returns the arcsine of the parameter.
  5246. *
  5247. * @tsl
  5248. * @function
  5249. * @param {Node | number} x - The parameter.
  5250. * @returns {Node}
  5251. */
  5252. const asin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ASIN ).setParameterLength( 1 );
  5253. /**
  5254. * Returns the inverse hyperbolic sine of the parameter.
  5255. *
  5256. * @tsl
  5257. * @function
  5258. * @param {Node | number} x - The parameter.
  5259. * @returns {Node}
  5260. */
  5261. const asinh = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ASINH ).setParameterLength( 1 );
  5262. /**
  5263. * Returns the arccosine of the parameter.
  5264. *
  5265. * @tsl
  5266. * @function
  5267. * @param {Node | number} x - The parameter.
  5268. * @returns {Node}
  5269. */
  5270. const acos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ACOS ).setParameterLength( 1 );
  5271. /**
  5272. * Returns the inverse hyperbolic cosine of the parameter.
  5273. *
  5274. * @tsl
  5275. * @function
  5276. * @param {Node | number} x - The parameter.
  5277. * @returns {Node}
  5278. */
  5279. const acosh = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ACOSH ).setParameterLength( 1 );
  5280. /**
  5281. * Returns the arc-tangent of the parameter.
  5282. * If two parameters are provided, the result is `atan2(y/x)`.
  5283. *
  5284. * @tsl
  5285. * @function
  5286. * @param {Node | number} y - The y parameter.
  5287. * @param {?(Node | number)} x - The x parameter.
  5288. * @returns {Node}
  5289. */
  5290. const atan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ATAN ).setParameterLength( 1, 2 );
  5291. /**
  5292. * Returns the inverse hyperbolic tangent of the parameter.
  5293. *
  5294. * @tsl
  5295. * @function
  5296. * @param {Node | number} x - The parameter.
  5297. * @returns {Node}
  5298. */
  5299. const atanh = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ATANH ).setParameterLength( 1 );
  5300. /**
  5301. * Returns the absolute value of the parameter.
  5302. *
  5303. * @tsl
  5304. * @function
  5305. * @param {Node | number} x - The parameter.
  5306. * @returns {Node}
  5307. */
  5308. const abs = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ABS ).setParameterLength( 1 );
  5309. /**
  5310. * Extracts the sign of the parameter.
  5311. *
  5312. * @tsl
  5313. * @function
  5314. * @param {Node | number} x - The parameter.
  5315. * @returns {Node}
  5316. */
  5317. const sign = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIGN ).setParameterLength( 1 );
  5318. /**
  5319. * Calculates the length of a vector.
  5320. *
  5321. * @tsl
  5322. * @function
  5323. * @param {Node} x - The parameter.
  5324. * @returns {Node<float>}
  5325. */
  5326. const length = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LENGTH ).setParameterLength( 1 );
  5327. /**
  5328. * Negates the value of the parameter (-x).
  5329. *
  5330. * @tsl
  5331. * @function
  5332. * @param {Node | number} x - The parameter.
  5333. * @returns {Node}
  5334. */
  5335. const negate = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NEGATE ).setParameterLength( 1 );
  5336. /**
  5337. * Return `1` minus the parameter.
  5338. *
  5339. * @tsl
  5340. * @function
  5341. * @param {Node | number} x - The parameter.
  5342. * @returns {Node}
  5343. */
  5344. const oneMinus = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ONE_MINUS ).setParameterLength( 1 );
  5345. /**
  5346. * Returns the partial derivative of the parameter with respect to x.
  5347. *
  5348. * @tsl
  5349. * @function
  5350. * @param {Node | number} x - The parameter.
  5351. * @returns {Node}
  5352. */
  5353. const dFdx = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDX ).setParameterLength( 1 );
  5354. /**
  5355. * Returns the partial derivative of the parameter with respect to y.
  5356. *
  5357. * @tsl
  5358. * @function
  5359. * @param {Node | number} x - The parameter.
  5360. * @returns {Node}
  5361. */
  5362. const dFdy = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDY ).setParameterLength( 1 );
  5363. /**
  5364. * Rounds the parameter to the nearest integer.
  5365. *
  5366. * @tsl
  5367. * @function
  5368. * @param {Node | number} x - The parameter.
  5369. * @returns {Node}
  5370. */
  5371. const round = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ROUND ).setParameterLength( 1 );
  5372. /**
  5373. * Returns the reciprocal of the parameter `(1/x)`.
  5374. *
  5375. * @tsl
  5376. * @function
  5377. * @param {Node | number} x - The parameter.
  5378. * @returns {Node}
  5379. */
  5380. const reciprocal = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RECIPROCAL ).setParameterLength( 1 );
  5381. /**
  5382. * Truncates the parameter, removing the fractional part.
  5383. *
  5384. * @tsl
  5385. * @function
  5386. * @param {Node | number} x - The parameter.
  5387. * @returns {Node}
  5388. */
  5389. const trunc = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRUNC ).setParameterLength( 1 );
  5390. /**
  5391. * Returns the sum of the absolute derivatives in x and y.
  5392. *
  5393. * @tsl
  5394. * @function
  5395. * @param {Node | number} x - The parameter.
  5396. * @returns {Node}
  5397. */
  5398. const fwidth = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FWIDTH ).setParameterLength( 1 );
  5399. /**
  5400. * Returns the transpose of a matrix.
  5401. *
  5402. * @tsl
  5403. * @function
  5404. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  5405. * @returns {Node}
  5406. */
  5407. const transpose = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSPOSE ).setParameterLength( 1 );
  5408. /**
  5409. * Returns the determinant of a matrix.
  5410. *
  5411. * @tsl
  5412. * @function
  5413. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  5414. * @returns {Node<float>}
  5415. */
  5416. const determinant = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DETERMINANT ).setParameterLength( 1 );
  5417. /**
  5418. * Returns the inverse of a matrix.
  5419. *
  5420. * @tsl
  5421. * @function
  5422. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  5423. * @returns {Node<mat2|mat3|mat4>}
  5424. */
  5425. const inverse = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE ).setParameterLength( 1 );
  5426. // 2 inputs
  5427. /**
  5428. * Returns the least of the given values.
  5429. *
  5430. * @tsl
  5431. * @function
  5432. * @param {...(Node | number)} values - The values to compare.
  5433. * @returns {Node}
  5434. */
  5435. const min$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIN ).setParameterLength( 2, Infinity );
  5436. /**
  5437. * Returns the greatest of the given values.
  5438. *
  5439. * @tsl
  5440. * @function
  5441. * @param {...(Node | number)} values - The values to compare.
  5442. * @returns {Node}
  5443. */
  5444. const max$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MAX ).setParameterLength( 2, Infinity );
  5445. /**
  5446. * Generate a step function by comparing two values.
  5447. *
  5448. * @tsl
  5449. * @function
  5450. * @param {Node | number} x - The y parameter.
  5451. * @param {Node | number} y - The x parameter.
  5452. * @returns {Node}
  5453. */
  5454. const step = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.STEP ).setParameterLength( 2 );
  5455. /**
  5456. * Calculates the reflection direction for an incident vector.
  5457. *
  5458. * @tsl
  5459. * @function
  5460. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5461. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  5462. * @returns {Node<vec2|vec3|vec4>}
  5463. */
  5464. const reflect = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFLECT ).setParameterLength( 2 );
  5465. /**
  5466. * Calculates the distance between two points.
  5467. *
  5468. * @tsl
  5469. * @function
  5470. * @param {Node<vec2|vec3|vec4>} x - The first point.
  5471. * @param {Node<vec2|vec3|vec4>} y - The second point.
  5472. * @returns {Node<float>}
  5473. */
  5474. const distance = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DISTANCE ).setParameterLength( 2 );
  5475. /**
  5476. * Calculates the absolute difference between two values.
  5477. *
  5478. * @tsl
  5479. * @function
  5480. * @param {Node | number} x - The first parameter.
  5481. * @param {Node | number} y - The second parameter.
  5482. * @returns {Node}
  5483. */
  5484. const difference = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DIFFERENCE ).setParameterLength( 2 );
  5485. /**
  5486. * Calculates the dot product of two vectors.
  5487. *
  5488. * @tsl
  5489. * @function
  5490. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  5491. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  5492. * @returns {Node<float>}
  5493. */
  5494. const dot = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DOT ).setParameterLength( 2 );
  5495. /**
  5496. * Calculates the cross product of two vectors.
  5497. *
  5498. * @tsl
  5499. * @function
  5500. * @param {Node<vec2|vec3>} x - The first vector.
  5501. * @param {Node<vec2|vec3>} y - The second vector.
  5502. * @returns {Node<float|vec3>}
  5503. */
  5504. const cross = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CROSS ).setParameterLength( 2 );
  5505. /**
  5506. * Return the value of the first parameter raised to the power of the second one.
  5507. *
  5508. * @tsl
  5509. * @function
  5510. * @param {Node | number} x - The first parameter.
  5511. * @param {Node | number} y - The second parameter.
  5512. * @returns {Node}
  5513. */
  5514. const pow = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.POW ).setParameterLength( 2 );
  5515. /**
  5516. * Returns the square of the parameter.
  5517. *
  5518. * @tsl
  5519. * @function
  5520. * @param {Node | number} x - The first parameter.
  5521. * @returns {Node}
  5522. */
  5523. const pow2 = ( x ) => mul( x, x );
  5524. /**
  5525. * Returns the cube of the parameter.
  5526. *
  5527. * @tsl
  5528. * @function
  5529. * @param {Node | number} x - The first parameter.
  5530. * @returns {Node}
  5531. */
  5532. const pow3 = ( x ) => mul( x, x, x );
  5533. /**
  5534. * Returns the fourth power of the parameter.
  5535. *
  5536. * @tsl
  5537. * @function
  5538. * @param {Node | number} x - The first parameter.
  5539. * @returns {Node}
  5540. */
  5541. const pow4 = ( x ) => mul( x, x, x, x );
  5542. /**
  5543. * Transforms the direction of a vector by a matrix and then normalizes the result.
  5544. *
  5545. * @tsl
  5546. * @function
  5547. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  5548. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  5549. * @returns {Node}
  5550. */
  5551. const transformDirection = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSFORM_DIRECTION ).setParameterLength( 2 );
  5552. /**
  5553. * Transforms a normal vector by the view matrix and then normalizes the result.
  5554. *
  5555. * The upper-left 3x3 of the view matrix is assumed to be orthonormal, so the
  5556. * normal can be transformed directly without involving the normal matrix.
  5557. *
  5558. * @tsl
  5559. * @function
  5560. * @param {Node<vec3>} normal - The normal vector, given in world space.
  5561. * @param {Node<mat3|mat4>} viewMatrix - The view matrix.
  5562. * @returns {Node<vec3>} The normal vector in view space.
  5563. */
  5564. const transformNormalByViewMatrix = ( normal, viewMatrix ) => normalize( mul( viewMatrix, vec4( vec3( normal ), 0.0 ) ).xyz );
  5565. /**
  5566. * Transforms a normal vector by the inverse of the view matrix and then normalizes the result.
  5567. *
  5568. * The upper-left 3x3 of the view matrix is assumed to be orthonormal, so post-multiplying
  5569. * by the view matrix is equivalent to pre-multiplying by its inverse.
  5570. *
  5571. * @tsl
  5572. * @function
  5573. * @param {Node<vec3>} normal - The normal vector, given in view space.
  5574. * @param {Node<mat3|mat4>} viewMatrix - The view matrix.
  5575. * @returns {Node<vec3>} The normal vector in world space.
  5576. */
  5577. const transformNormalByInverseViewMatrix = ( normal, viewMatrix ) => normalize( vec4( vec3( normal ), 0.0 ).mul( viewMatrix ).xyz );
  5578. /**
  5579. * Returns the cube root of a number.
  5580. *
  5581. * @tsl
  5582. * @function
  5583. * @param {Node | number} a - The first parameter.
  5584. * @returns {Node}
  5585. */
  5586. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  5587. /**
  5588. * Calculate the squared length of a vector.
  5589. *
  5590. * @tsl
  5591. * @function
  5592. * @param {Node<vec2|vec3|vec4>} a - The vector.
  5593. * @returns {Node<float>}
  5594. */
  5595. const lengthSq = ( a ) => dot( a, a );
  5596. /**
  5597. * Linearly interpolates between two values.
  5598. *
  5599. * @tsl
  5600. * @function
  5601. * @param {Node | number} a - The first parameter.
  5602. * @param {Node | number} b - The second parameter.
  5603. * @param {Node | number} t - The interpolation value.
  5604. * @returns {Node}
  5605. */
  5606. const mix = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIX ).setParameterLength( 3 );
  5607. /**
  5608. * Constrains a value to lie between two further values.
  5609. *
  5610. * @tsl
  5611. * @function
  5612. * @param {Node | number} value - The value to constrain.
  5613. * @param {Node | number} [low=0] - The lower bound.
  5614. * @param {Node | number} [high=1] - The upper bound.
  5615. * @returns {Node}
  5616. */
  5617. const clamp = ( value, low = 0, high = 1 ) => new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) );
  5618. /**
  5619. * Constrains a value between `0` and `1`.
  5620. *
  5621. * @tsl
  5622. * @function
  5623. * @param {Node | number} value - The value to constrain.
  5624. * @returns {Node}
  5625. */
  5626. const saturate = ( value ) => clamp( value );
  5627. /**
  5628. * Calculates the refraction direction for an incident vector.
  5629. *
  5630. * @tsl
  5631. * @function
  5632. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5633. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  5634. * @param {Node<float>} eta - The ratio of indices of refraction.
  5635. * @returns {Node<vec2|vec3|vec4>}
  5636. */
  5637. const refract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFRACT ).setParameterLength( 3 );
  5638. /**
  5639. * Performs a Hermite interpolation between two values.
  5640. *
  5641. * @tsl
  5642. * @function
  5643. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5644. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5645. * @param {Node | number} x - The source value for interpolation.
  5646. * @returns {Node}
  5647. */
  5648. const smoothstep = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SMOOTHSTEP ).setParameterLength( 3 );
  5649. /**
  5650. * Returns a vector pointing in the same direction as another.
  5651. *
  5652. * @tsl
  5653. * @function
  5654. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  5655. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5656. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  5657. * @returns {Node<vec2|vec3|vec4>}
  5658. */
  5659. const faceForward = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FACEFORWARD ).setParameterLength( 3 );
  5660. /**
  5661. * Returns a random value for the given uv.
  5662. *
  5663. * @tsl
  5664. * @function
  5665. * @param {Node<vec2>} uv - The uv node.
  5666. * @returns {Node<float>}
  5667. */
  5668. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  5669. const a = 12.9898, b = 78.233, c = 43758.5453;
  5670. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  5671. return fract( sin( sn ).mul( c ) );
  5672. } );
  5673. /**
  5674. * Alias for `mix()` with a different parameter order.
  5675. *
  5676. * @tsl
  5677. * @function
  5678. * @param {Node | number} t - The interpolation value.
  5679. * @param {Node | number} e1 - The first parameter.
  5680. * @param {Node | number} e2 - The second parameter.
  5681. * @returns {Node}
  5682. */
  5683. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  5684. /**
  5685. * Alias for `smoothstep()` with a different parameter order.
  5686. *
  5687. * @tsl
  5688. * @function
  5689. * @param {Node | number} x - The source value for interpolation.
  5690. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5691. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5692. * @returns {Node}
  5693. */
  5694. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  5695. /**
  5696. * Alias for `step()` with a different parameter order.
  5697. *
  5698. * @tsl
  5699. * @function
  5700. * @param {Node | number} x - The source value for interpolation.
  5701. * @param {Node | number} edge - The edge value.
  5702. * @returns {Node}
  5703. */
  5704. const stepElement = ( x, edge ) => step( edge, x );
  5705. // GLSL alias function
  5706. const faceforward = faceForward;
  5707. const inversesqrt = inverseSqrt;
  5708. // Method chaining
  5709. addMethodChaining( 'all', all );
  5710. addMethodChaining( 'any', any );
  5711. addMethodChaining( 'radians', radians );
  5712. addMethodChaining( 'degrees', degrees );
  5713. addMethodChaining( 'exp', exp );
  5714. addMethodChaining( 'exp2', exp2 );
  5715. addMethodChaining( 'log', log );
  5716. addMethodChaining( 'log2', log2 );
  5717. addMethodChaining( 'sqrt', sqrt );
  5718. addMethodChaining( 'inverseSqrt', inverseSqrt );
  5719. addMethodChaining( 'floor', floor );
  5720. addMethodChaining( 'ceil', ceil );
  5721. addMethodChaining( 'normalize', normalize );
  5722. addMethodChaining( 'fract', fract );
  5723. addMethodChaining( 'sin', sin );
  5724. addMethodChaining( 'sinh', sinh );
  5725. addMethodChaining( 'cos', cos );
  5726. addMethodChaining( 'cosh', cosh );
  5727. addMethodChaining( 'tan', tan );
  5728. addMethodChaining( 'tanh', tanh );
  5729. addMethodChaining( 'asin', asin );
  5730. addMethodChaining( 'asinh', asinh );
  5731. addMethodChaining( 'acos', acos );
  5732. addMethodChaining( 'acosh', acosh );
  5733. addMethodChaining( 'atan', atan );
  5734. addMethodChaining( 'atanh', atanh );
  5735. addMethodChaining( 'abs', abs );
  5736. addMethodChaining( 'sign', sign );
  5737. addMethodChaining( 'length', length );
  5738. addMethodChaining( 'lengthSq', lengthSq );
  5739. addMethodChaining( 'negate', negate );
  5740. addMethodChaining( 'oneMinus', oneMinus );
  5741. addMethodChaining( 'dFdx', dFdx );
  5742. addMethodChaining( 'dFdy', dFdy );
  5743. addMethodChaining( 'round', round );
  5744. addMethodChaining( 'reciprocal', reciprocal );
  5745. addMethodChaining( 'trunc', trunc );
  5746. addMethodChaining( 'fwidth', fwidth );
  5747. addMethodChaining( 'min', min$1 );
  5748. addMethodChaining( 'max', max$1 );
  5749. addMethodChaining( 'step', stepElement );
  5750. addMethodChaining( 'reflect', reflect );
  5751. addMethodChaining( 'distance', distance );
  5752. addMethodChaining( 'dot', dot );
  5753. addMethodChaining( 'cross', cross );
  5754. addMethodChaining( 'pow', pow );
  5755. addMethodChaining( 'pow2', pow2 );
  5756. addMethodChaining( 'pow3', pow3 );
  5757. addMethodChaining( 'pow4', pow4 );
  5758. addMethodChaining( 'transformDirection', transformDirection );
  5759. addMethodChaining( 'transformNormalByViewMatrix', transformNormalByViewMatrix );
  5760. addMethodChaining( 'transformNormalByInverseViewMatrix', transformNormalByInverseViewMatrix );
  5761. addMethodChaining( 'mix', mixElement );
  5762. addMethodChaining( 'clamp', clamp );
  5763. addMethodChaining( 'refract', refract );
  5764. addMethodChaining( 'smoothstep', smoothstepElement );
  5765. addMethodChaining( 'faceForward', faceForward );
  5766. addMethodChaining( 'difference', difference );
  5767. addMethodChaining( 'saturate', saturate );
  5768. addMethodChaining( 'cbrt', cbrt );
  5769. addMethodChaining( 'transpose', transpose );
  5770. addMethodChaining( 'determinant', determinant );
  5771. addMethodChaining( 'inverse', inverse );
  5772. addMethodChaining( 'rand', rand );
  5773. /**
  5774. * Represents a logical `if/else` statement. Can be used as an alternative
  5775. * to the `If()`/`Else()` syntax.
  5776. *
  5777. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  5778. * determine the outcome of the entire statement.
  5779. *
  5780. * ```js
  5781. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  5782. * ```
  5783. *
  5784. * @augments Node
  5785. */
  5786. class ConditionalNode extends Node {
  5787. static get type() {
  5788. return 'ConditionalNode';
  5789. }
  5790. /**
  5791. * Constructs a new conditional node.
  5792. *
  5793. * @param {Node} condNode - The node that defines the condition.
  5794. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5795. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5796. */
  5797. constructor( condNode, ifNode, elseNode = null ) {
  5798. super();
  5799. /**
  5800. * The node that defines the condition.
  5801. *
  5802. * @type {Node}
  5803. */
  5804. this.condNode = condNode;
  5805. /**
  5806. * The node that is evaluate when the condition ends up `true`.
  5807. *
  5808. * @type {Node}
  5809. */
  5810. this.ifNode = ifNode;
  5811. /**
  5812. * The node that is evaluate when the condition ends up `false`.
  5813. *
  5814. * @type {?Node}
  5815. * @default null
  5816. */
  5817. this.elseNode = elseNode;
  5818. }
  5819. /**
  5820. * This method is overwritten since the node type is inferred from the if/else
  5821. * nodes.
  5822. *
  5823. * @param {NodeBuilder} builder - The current node builder.
  5824. * @return {string} The node type.
  5825. */
  5826. generateNodeType( builder ) {
  5827. const { ifNode, elseNode } = builder.getNodeProperties( this );
  5828. if ( ifNode === undefined ) {
  5829. // fallback setup
  5830. builder.flowBuildStage( this, 'setup' );
  5831. return this.getNodeType( builder );
  5832. }
  5833. const ifType = ifNode.getNodeType( builder );
  5834. if ( elseNode !== null ) {
  5835. const elseType = elseNode.getNodeType( builder );
  5836. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  5837. return elseType;
  5838. }
  5839. }
  5840. return ifType;
  5841. }
  5842. setup( builder ) {
  5843. const condNode = this.condNode;
  5844. const ifNode = this.ifNode.isolate();
  5845. const elseNode = this.elseNode ? this.elseNode.isolate() : null;
  5846. //
  5847. const currentNodeBlock = builder.context.nodeBlock;
  5848. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  5849. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  5850. //
  5851. const isUniformFlow = builder.context.uniformFlow;
  5852. const properties = builder.getNodeProperties( this );
  5853. properties.condNode = condNode;
  5854. properties.ifNode = isUniformFlow ? ifNode : ifNode.context( { nodeBlock: ifNode } );
  5855. properties.elseNode = elseNode ? ( isUniformFlow ? elseNode : elseNode.context( { nodeBlock: elseNode } ) ) : null;
  5856. }
  5857. generate( builder, output ) {
  5858. const type = this.getNodeType( builder );
  5859. const nodeData = builder.getDataFromNode( this );
  5860. if ( nodeData.nodeProperty !== undefined ) {
  5861. return nodeData.nodeProperty;
  5862. }
  5863. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  5864. const functionNode = builder.currentFunctionNode;
  5865. const needsOutput = output !== 'void';
  5866. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  5867. nodeData.nodeProperty = nodeProperty;
  5868. const nodeSnippet = condNode.build( builder, 'bool' );
  5869. const isUniformFlow = builder.context.uniformFlow;
  5870. if ( isUniformFlow && elseNode !== null ) {
  5871. const ifSnippet = ifNode.build( builder, type );
  5872. const elseSnippet = elseNode.build( builder, type );
  5873. const mathSnippet = builder.getTernary( nodeSnippet, ifSnippet, elseSnippet );
  5874. // TODO: If node property already exists return something else
  5875. return builder.format( mathSnippet, type, output );
  5876. }
  5877. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  5878. let ifSnippet = ifNode.build( builder, type );
  5879. if ( ifSnippet ) {
  5880. if ( needsOutput ) {
  5881. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  5882. } else {
  5883. ifSnippet = 'return ' + ifSnippet + ';';
  5884. if ( functionNode === null ) {
  5885. warn( 'TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.', this.stackTrace );
  5886. ifSnippet = '// ' + ifSnippet;
  5887. }
  5888. }
  5889. }
  5890. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  5891. if ( elseNode !== null ) {
  5892. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  5893. let elseSnippet = elseNode.build( builder, type );
  5894. if ( elseSnippet ) {
  5895. if ( needsOutput ) {
  5896. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  5897. } else {
  5898. elseSnippet = 'return ' + elseSnippet + ';';
  5899. if ( functionNode === null ) {
  5900. warn( 'TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.', this.stackTrace );
  5901. elseSnippet = '// ' + elseSnippet;
  5902. }
  5903. }
  5904. }
  5905. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  5906. } else {
  5907. builder.addFlowCode( '\n\n' );
  5908. }
  5909. return builder.format( nodeProperty, type, output );
  5910. }
  5911. }
  5912. /**
  5913. * TSL function for creating a conditional node.
  5914. *
  5915. * @tsl
  5916. * @function
  5917. * @param {Node} condNode - The node that defines the condition.
  5918. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5919. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5920. * @returns {ConditionalNode}
  5921. */
  5922. const select = /*@__PURE__*/ nodeProxy( ConditionalNode ).setParameterLength( 2, 3 );
  5923. addMethodChaining( 'select', select );
  5924. /**
  5925. * This node can be used as a context management component for another node.
  5926. * {@link NodeBuilder} performs its node building process in a specific context and
  5927. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  5928. *
  5929. * ```js
  5930. *node.context( { getUV: () => customCoord } );
  5931. *\// or
  5932. *material.contextNode = context( { getUV: () => customCoord } );
  5933. *\// or
  5934. *renderer.contextNode = context( { getUV: () => customCoord } );
  5935. *\// or
  5936. *scenePass.contextNode = context( { getUV: () => customCoord } );
  5937. *```
  5938. * @augments Node
  5939. */
  5940. class ContextNode extends Node {
  5941. static get type() {
  5942. return 'ContextNode';
  5943. }
  5944. /**
  5945. * Constructs a new context node.
  5946. *
  5947. * @param {Node} node - The node whose context should be modified.
  5948. * @param {Object} [value={}] - The modified context data.
  5949. */
  5950. constructor( node = null, value = {} ) {
  5951. super();
  5952. /**
  5953. * This flag can be used for type testing.
  5954. *
  5955. * @type {boolean}
  5956. * @readonly
  5957. * @default true
  5958. */
  5959. this.isContextNode = true;
  5960. /**
  5961. * The node whose context should be modified.
  5962. *
  5963. * @type {Node}
  5964. */
  5965. this.node = node;
  5966. /**
  5967. * The modified context data.
  5968. *
  5969. * @type {Object}
  5970. * @default {}
  5971. */
  5972. this.value = value;
  5973. }
  5974. /**
  5975. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  5976. *
  5977. * @return {Node} A reference to {@link ContextNode#node}.
  5978. */
  5979. getScope() {
  5980. return this.node.getScope();
  5981. }
  5982. /**
  5983. * This method is overwritten to ensure it returns the type of {@link ContextNode#node}.
  5984. *
  5985. * @param {NodeBuilder} builder - The current node builder.
  5986. * @return {string} The node type.
  5987. */
  5988. generateNodeType( builder ) {
  5989. return this.node.getNodeType( builder );
  5990. }
  5991. /**
  5992. * Gathers the context data from all parent context nodes.
  5993. *
  5994. * @return {Object} The gathered context data.
  5995. */
  5996. getFlowContextData() {
  5997. const children = [];
  5998. this.traverse( ( node ) => {
  5999. if ( node.isContextNode === true ) {
  6000. children.push( node.value );
  6001. }
  6002. } );
  6003. return Object.assign( {}, ...children );
  6004. }
  6005. /**
  6006. * This method is overwritten to ensure it returns the member type of {@link ContextNode#node}.
  6007. *
  6008. * @param {NodeBuilder} builder - The current node builder.
  6009. * @param {string} name - The member name.
  6010. * @returns {string} The member type.
  6011. */
  6012. getMemberType( builder, name ) {
  6013. return this.node.getMemberType( builder, name );
  6014. }
  6015. analyze( builder ) {
  6016. const previousContext = builder.addContext( this.value );
  6017. this.node.build( builder );
  6018. builder.setContext( previousContext );
  6019. }
  6020. setup( builder ) {
  6021. const previousContext = builder.addContext( this.value );
  6022. this.node.build( builder );
  6023. builder.setContext( previousContext );
  6024. }
  6025. generate( builder, output ) {
  6026. const previousContext = builder.addContext( this.value );
  6027. const snippet = this.node.build( builder, output );
  6028. builder.setContext( previousContext );
  6029. return snippet;
  6030. }
  6031. }
  6032. /**
  6033. * TSL function for creating a context node.
  6034. *
  6035. * @tsl
  6036. * @function
  6037. * @param {Node|Object} [nodeOrValue={}] - The node whose context should be modified or the modified context data.
  6038. * @param {Object} [value={}] - The modified context data.
  6039. * @returns {ContextNode}
  6040. */
  6041. const context = ( nodeOrValue = null, value = {} ) => {
  6042. let node = nodeOrValue;
  6043. if ( node === null || node.isNode !== true ) {
  6044. value = node || value;
  6045. node = null;
  6046. }
  6047. return new ContextNode( node, value );
  6048. };
  6049. /**
  6050. * TSL function for defining a uniformFlow context value for a given node.
  6051. *
  6052. * @tsl
  6053. * @function
  6054. * @param {Node} node - The node whose dependencies should all execute within a uniform control-flow path.
  6055. * @returns {ContextNode}
  6056. */
  6057. const uniformFlow = ( node ) => context( node, { uniformFlow: true } );
  6058. /**
  6059. * TSL function for defining a name for the context value for a given node.
  6060. *
  6061. * @tsl
  6062. * @function
  6063. * @param {Node} node - The node whose context should be modified.
  6064. * @param {string} name - The name to set.
  6065. * @returns {ContextNode}
  6066. */
  6067. const setName = ( node, name ) => context( node, { nodeName: name } );
  6068. /**
  6069. * TSL function for defining a built-in shadow context for a given node.
  6070. *
  6071. * @tsl
  6072. * @function
  6073. * @param {ShadowNode} shadowNode - The shadow node representing the light's shadow.
  6074. * @param {Light} light - The light associated with the shadow.
  6075. * @param {Node} [node=null] - The node whose context should be modified.
  6076. * @returns {ContextNode}
  6077. */
  6078. function builtinShadowContext( shadowNode, light, node = null ) {
  6079. return context( node, {
  6080. getShadow: ( { light: shadowLight, shadowColorNode } ) => {
  6081. if ( light === shadowLight ) {
  6082. return shadowColorNode.mul( shadowNode );
  6083. }
  6084. return shadowColorNode;
  6085. }
  6086. } );
  6087. }
  6088. /**
  6089. * TSL function for defining a built-in ambient occlusion context for a given node.
  6090. *
  6091. * @tsl
  6092. * @function
  6093. * @param {Node} aoNode - The ambient occlusion value node to apply.
  6094. * @param {Node} [node=null] - The node whose context should be modified.
  6095. * @returns {ContextNode}
  6096. */
  6097. function builtinAOContext( aoNode, node = null ) {
  6098. return context( node, {
  6099. getAO: ( inputNode, { material } ) => {
  6100. if ( material.transparent === true ) return inputNode;
  6101. return inputNode !== null ? inputNode.mul( aoNode ) : aoNode;
  6102. }
  6103. } );
  6104. }
  6105. /**
  6106. * TSL function for defining a label context value for a given node.
  6107. *
  6108. * @tsl
  6109. * @function
  6110. * @deprecated
  6111. * @param {Node} node - The node whose context should be modified.
  6112. * @param {string} name - The name/label to set.
  6113. * @returns {ContextNode}
  6114. */
  6115. function label( node, name ) {
  6116. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  6117. return setName( node, name );
  6118. }
  6119. addMethodChaining( 'context', context );
  6120. addMethodChaining( 'label', label );
  6121. addMethodChaining( 'uniformFlow', uniformFlow );
  6122. addMethodChaining( 'setName', setName );
  6123. addMethodChaining( 'builtinShadowContext', ( node, shadowNode, light ) => builtinShadowContext( shadowNode, light, node ) );
  6124. addMethodChaining( 'builtinAOContext', ( node, aoValue ) => builtinAOContext( aoValue, node ) );
  6125. /**
  6126. * Class for representing shader variables as nodes. Variables are created from
  6127. * existing nodes like the following:
  6128. *
  6129. * ```js
  6130. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  6131. * ```
  6132. *
  6133. * @augments Node
  6134. */
  6135. class VarNode extends Node {
  6136. static get type() {
  6137. return 'VarNode';
  6138. }
  6139. /**
  6140. * Constructs a new variable node.
  6141. *
  6142. * @param {Node} node - The node for which a variable should be created.
  6143. * @param {?string} [name=null] - The name of the variable in the shader.
  6144. * @param {boolean} [readOnly=false] - The read-only flag.
  6145. */
  6146. constructor( node, name = null, readOnly = false ) {
  6147. super();
  6148. /**
  6149. * The node for which a variable should be created.
  6150. *
  6151. * @type {Node}
  6152. */
  6153. this.node = node;
  6154. /**
  6155. * The name of the variable in the shader. If no name is defined,
  6156. * the node system auto-generates one.
  6157. *
  6158. * @type {?string}
  6159. * @default null
  6160. */
  6161. this.name = name;
  6162. /**
  6163. * `VarNode` sets this property to `true` by default.
  6164. *
  6165. * @type {boolean}
  6166. * @default true
  6167. */
  6168. this.global = true;
  6169. /**
  6170. * This flag can be used for type testing.
  6171. *
  6172. * @type {boolean}
  6173. * @readonly
  6174. * @default true
  6175. */
  6176. this.isVarNode = true;
  6177. /**
  6178. *
  6179. * The read-only flag.
  6180. *
  6181. * @type {boolean}
  6182. * @default false
  6183. */
  6184. this.readOnly = readOnly;
  6185. /**
  6186. *
  6187. * Add this flag to the node system to indicate that this node require parents.
  6188. *
  6189. * @type {boolean}
  6190. * @default true
  6191. */
  6192. this.parents = true;
  6193. /**
  6194. * This flag is used to indicate that this node is used for intent.
  6195. *
  6196. * @type {boolean}
  6197. * @default false
  6198. */
  6199. this.intent = false;
  6200. }
  6201. /**
  6202. * Sets the intent flag for this node.
  6203. *
  6204. * This flag is used to indicate that this node is used for intent
  6205. * and should not be built directly. Instead, it is used to indicate that
  6206. * the node should be treated as a variable intent.
  6207. *
  6208. * It's useful for assigning variables without needing creating a new variable node.
  6209. *
  6210. * @param {boolean} value - The value to set for the intent flag.
  6211. * @returns {VarNode} This node.
  6212. */
  6213. setIntent( value ) {
  6214. this.intent = value;
  6215. return this;
  6216. }
  6217. /**
  6218. * Checks if this node is used for intent.
  6219. *
  6220. * @param {NodeBuilder} builder - The node builder.
  6221. * @returns {boolean} Whether this node is used for intent.
  6222. */
  6223. isIntent( builder ) {
  6224. const data = builder.getDataFromNode( this );
  6225. if ( data.forceDeclaration === true ) return false;
  6226. return this.intent;
  6227. }
  6228. /**
  6229. * Returns the intent flag of this node.
  6230. *
  6231. * @return {boolean} The intent flag.
  6232. */
  6233. getIntent() {
  6234. return this.intent;
  6235. }
  6236. getMemberType( builder, name ) {
  6237. return this.node.getMemberType( builder, name );
  6238. }
  6239. getElementType( builder ) {
  6240. return this.node.getElementType( builder );
  6241. }
  6242. generateNodeType( builder ) {
  6243. return this.node.getNodeType( builder );
  6244. }
  6245. getArrayCount( builder ) {
  6246. return this.node.getArrayCount( builder );
  6247. }
  6248. isAssign( builder ) {
  6249. const data = builder.getDataFromNode( this );
  6250. return data.assign;
  6251. }
  6252. build( ...params ) {
  6253. const builder = params[ 0 ];
  6254. const refNode = this.getShared( builder );
  6255. if ( this !== refNode ) {
  6256. return refNode.build( ...params );
  6257. }
  6258. if ( this._hasStack( builder ) === false && builder.buildStage === 'setup' ) {
  6259. if ( builder.context.nodeLoop || builder.context.nodeBlock ) {
  6260. let addBefore = false;
  6261. if ( this.node.isShaderCallNodeInternal && this.node.shaderNode.getLayout() === null ) {
  6262. if ( builder.fnCall && builder.fnCall.shaderNode ) {
  6263. const shaderNodeData = builder.getDataFromNode( this.node.shaderNode );
  6264. if ( shaderNodeData.hasLoop ) {
  6265. const data = builder.getDataFromNode( this );
  6266. data.forceDeclaration = true;
  6267. addBefore = true;
  6268. }
  6269. }
  6270. }
  6271. const baseStack = builder.getBaseStack();
  6272. if ( addBefore ) {
  6273. baseStack.addToStackBefore( this );
  6274. } else {
  6275. baseStack.addToStack( this );
  6276. }
  6277. }
  6278. }
  6279. if ( this.isIntent( builder ) ) {
  6280. if ( this.isAssign( builder ) !== true ) {
  6281. return this.node.build( ...params );
  6282. }
  6283. }
  6284. return super.build( ...params );
  6285. }
  6286. generate( builder ) {
  6287. const { node, name, readOnly } = this;
  6288. const { renderer } = builder;
  6289. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  6290. let isDeterministic = false;
  6291. let shouldTreatAsReadOnly = false;
  6292. if ( readOnly ) {
  6293. isDeterministic = builder.isDeterministic( node );
  6294. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  6295. }
  6296. const nodeType = this.getNodeType( builder );
  6297. if ( nodeType == 'void' ) {
  6298. if ( this.isIntent( builder ) !== true ) {
  6299. error( 'TSL: ".toVar()" can not be used with void type.', this.stackTrace );
  6300. }
  6301. const snippet = node.build( builder );
  6302. return snippet;
  6303. }
  6304. const vectorType = builder.getVectorType( nodeType );
  6305. const snippet = node.build( builder, vectorType );
  6306. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  6307. const propertyName = builder.getPropertyName( nodeVar );
  6308. let declarationPrefix = propertyName;
  6309. if ( shouldTreatAsReadOnly ) {
  6310. if ( isWebGPUBackend ) {
  6311. declarationPrefix = isDeterministic
  6312. ? `const ${ propertyName }`
  6313. : `let ${ propertyName }`;
  6314. } else {
  6315. const count = node.getArrayCount( builder );
  6316. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  6317. }
  6318. }
  6319. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  6320. return propertyName;
  6321. }
  6322. _hasStack( builder ) {
  6323. const nodeData = builder.getDataFromNode( this );
  6324. return nodeData.stack !== undefined;
  6325. }
  6326. }
  6327. /**
  6328. * TSL function for creating a var node.
  6329. *
  6330. * @tsl
  6331. * @function
  6332. * @param {Node} node - The node for which a variable should be created.
  6333. * @param {?string} name - The name of the variable in the shader.
  6334. * @returns {VarNode}
  6335. */
  6336. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  6337. /**
  6338. * TSL function for creating a var node.
  6339. *
  6340. * @tsl
  6341. * @function
  6342. * @param {Node} node - The node for which a variable should be created.
  6343. * @param {?string} name - The name of the variable in the shader.
  6344. * @returns {VarNode}
  6345. */
  6346. const Var = ( node, name = null ) => createVar( node, name ).toStack();
  6347. /**
  6348. * TSL function for creating a const node.
  6349. *
  6350. * @tsl
  6351. * @function
  6352. * @param {Node} node - The node for which a constant should be created.
  6353. * @param {?string} name - The name of the constant in the shader.
  6354. * @returns {VarNode}
  6355. */
  6356. const Const = ( node, name = null ) => createVar( node, name, true ).toStack();
  6357. //
  6358. //
  6359. /**
  6360. * TSL function for creating a var intent node.
  6361. *
  6362. * @tsl
  6363. * @function
  6364. * @param {Node} node - The node for which a variable should be created.
  6365. * @param {?string} name - The name of the variable in the shader.
  6366. * @returns {VarNode}
  6367. */
  6368. const VarIntent = ( node ) => {
  6369. return createVar( node ).setIntent( true ).toStack();
  6370. };
  6371. // Method chaining
  6372. addMethodChaining( 'toVar', Var );
  6373. addMethodChaining( 'toConst', Const );
  6374. addMethodChaining( 'toVarIntent', VarIntent );
  6375. /**
  6376. * This node is used to build a sub-build in the node system.
  6377. *
  6378. * @augments Node
  6379. * @param {Node} node - The node to be built in the sub-build.
  6380. * @param {string} name - The name of the sub-build.
  6381. * @param {?string} [nodeType=null] - The type of the node, if known.
  6382. */
  6383. class SubBuildNode extends Node {
  6384. static get type() {
  6385. return 'SubBuild';
  6386. }
  6387. constructor( node, name, nodeType = null ) {
  6388. super( nodeType );
  6389. /**
  6390. * The node to be built in the sub-build.
  6391. *
  6392. * @type {Node}
  6393. */
  6394. this.node = node;
  6395. /**
  6396. * The name of the sub-build.
  6397. *
  6398. * @type {string}
  6399. */
  6400. this.name = name;
  6401. /**
  6402. * This flag can be used for type testing.
  6403. *
  6404. * @type {boolean}
  6405. * @readonly
  6406. * @default true
  6407. */
  6408. this.isSubBuildNode = true;
  6409. }
  6410. generateNodeType( builder ) {
  6411. if ( this.nodeType !== null ) return this.nodeType;
  6412. builder.addSubBuild( this.name );
  6413. const nodeType = this.node.getNodeType( builder );
  6414. builder.removeSubBuild();
  6415. return nodeType;
  6416. }
  6417. build( builder, ...params ) {
  6418. builder.addSubBuild( this.name );
  6419. const data = this.node.build( builder, ...params );
  6420. builder.removeSubBuild();
  6421. return data;
  6422. }
  6423. }
  6424. /**
  6425. * Creates a new sub-build node.
  6426. *
  6427. * @tsl
  6428. * @function
  6429. * @param {Node} node - The node to be built in the sub-build.
  6430. * @param {string} name - The name of the sub-build.
  6431. * @param {?string} [type=null] - The type of the node, if known.
  6432. * @returns {Node} A node object wrapping the SubBuildNode instance.
  6433. */
  6434. const subBuild = ( node, name, type = null ) => new SubBuildNode( nodeObject( node ), name, type );
  6435. /**
  6436. * Class for representing shader varyings as nodes. Varyings are create from
  6437. * existing nodes like the following:
  6438. *
  6439. * ```js
  6440. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  6441. * ```
  6442. *
  6443. * @augments Node
  6444. */
  6445. class VaryingNode extends Node {
  6446. static get type() {
  6447. return 'VaryingNode';
  6448. }
  6449. /**
  6450. * Constructs a new varying node.
  6451. *
  6452. * @param {Node} node - The node for which a varying should be created.
  6453. * @param {?string} name - The name of the varying in the shader.
  6454. */
  6455. constructor( node, name = null ) {
  6456. super();
  6457. /**
  6458. * The node for which a varying should be created.
  6459. *
  6460. * @type {Node}
  6461. */
  6462. this.node = subBuild( node, 'VERTEX' );
  6463. /**
  6464. * The name of the varying in the shader. If no name is defined,
  6465. * the node system auto-generates one.
  6466. *
  6467. * @type {?string}
  6468. * @default null
  6469. */
  6470. this.name = name;
  6471. /**
  6472. * This flag can be used for type testing.
  6473. *
  6474. * @type {boolean}
  6475. * @readonly
  6476. * @default true
  6477. */
  6478. this.isVaryingNode = true;
  6479. /**
  6480. * The interpolation type of the varying data.
  6481. *
  6482. * @type {?string}
  6483. * @default null
  6484. */
  6485. this.interpolationType = null;
  6486. /**
  6487. * The interpolation sampling type of varying data.
  6488. *
  6489. * @type {?string}
  6490. * @default null
  6491. */
  6492. this.interpolationSampling = null;
  6493. /**
  6494. * This flag is used for global cache.
  6495. *
  6496. * @type {boolean}
  6497. * @default true
  6498. */
  6499. this.global = true;
  6500. }
  6501. /**
  6502. * Defines the interpolation type of the varying.
  6503. *
  6504. * @param {string} type - The interpolation type.
  6505. * @param {?string} sampling - The interpolation sampling type
  6506. * @return {VaryingNode} A reference to this node.
  6507. */
  6508. setInterpolation( type, sampling = null ) {
  6509. this.interpolationType = type;
  6510. this.interpolationSampling = sampling;
  6511. return this;
  6512. }
  6513. getHash( builder ) {
  6514. return this.name || super.getHash( builder );
  6515. }
  6516. generateNodeType( builder ) {
  6517. // VaryingNode is auto type
  6518. return this.node.getNodeType( builder );
  6519. }
  6520. /**
  6521. * This method performs the setup of a varying node with the current node builder.
  6522. *
  6523. * @param {NodeBuilder} builder - The current node builder.
  6524. * @return {NodeVarying} The node varying from the node builder.
  6525. */
  6526. setupVarying( builder ) {
  6527. const properties = builder.getNodeProperties( this );
  6528. let varying = properties.varying;
  6529. if ( varying === undefined ) {
  6530. const name = this.name;
  6531. const type = this.getNodeType( builder );
  6532. const interpolationType = this.interpolationType;
  6533. const interpolationSampling = this.interpolationSampling;
  6534. properties.varying = varying = builder.getVaryingFromNode( this, name, type, interpolationType, interpolationSampling );
  6535. properties.node = subBuild( this.node, 'VERTEX' );
  6536. }
  6537. // this property can be used to check if the varying can be optimized for a variable
  6538. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  6539. return varying;
  6540. }
  6541. setup( builder ) {
  6542. this.setupVarying( builder );
  6543. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  6544. }
  6545. analyze( builder ) {
  6546. this.setupVarying( builder );
  6547. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  6548. }
  6549. generate( builder ) {
  6550. const propertyKey = builder.getSubBuildProperty( 'property', builder.currentStack );
  6551. const properties = builder.getNodeProperties( this );
  6552. const varying = this.setupVarying( builder );
  6553. if ( properties[ propertyKey ] === undefined ) {
  6554. const type = this.getNodeType( builder );
  6555. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  6556. if ( builder.shaderStage === NodeShaderStage.VERTEX ) {
  6557. const snippet = properties.node.build( builder, type );
  6558. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  6559. } else {
  6560. // force node run in vertex stage
  6561. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, properties.node, type, propertyName );
  6562. }
  6563. properties[ propertyKey ] = propertyName;
  6564. }
  6565. return builder.getPropertyName( varying );
  6566. }
  6567. }
  6568. /**
  6569. * TSL function for creating a varying node.
  6570. *
  6571. * @tsl
  6572. * @function
  6573. * @param {Node} node - The node for which a varying should be created.
  6574. * @param {?string} name - The name of the varying in the shader.
  6575. * @returns {VaryingNode}
  6576. */
  6577. const varying = /*@__PURE__*/ nodeProxy( VaryingNode ).setParameterLength( 1, 2 );
  6578. /**
  6579. * Computes a node in the vertex stage.
  6580. *
  6581. * @tsl
  6582. * @function
  6583. * @param {Node} node - The node which should be executed in the vertex stage.
  6584. * @returns {VaryingNode}
  6585. */
  6586. const vertexStage = ( node ) => varying( node );
  6587. addMethodChaining( 'toVarying', varying );
  6588. addMethodChaining( 'toVertexStage', vertexStage );
  6589. /**
  6590. * Converts the given color value from sRGB to linear-sRGB color space.
  6591. *
  6592. * @tsl
  6593. * @function
  6594. * @param {Node<vec3>} color - The sRGB color.
  6595. * @return {Node<vec3>} The linear-sRGB color.
  6596. */
  6597. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  6598. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  6599. const b = color.mul( 0.0773993808 );
  6600. const factor = color.lessThanEqual( 0.04045 );
  6601. const rgbResult = mix( a, b, factor );
  6602. return rgbResult;
  6603. } ).setLayout( {
  6604. name: 'sRGBTransferEOTF',
  6605. type: 'vec3',
  6606. inputs: [
  6607. { name: 'color', type: 'vec3' }
  6608. ]
  6609. } );
  6610. /**
  6611. * Converts the given color value from linear-sRGB to sRGB color space.
  6612. *
  6613. * @tsl
  6614. * @function
  6615. * @param {Node<vec3>} color - The linear-sRGB color.
  6616. * @return {Node<vec3>} The sRGB color.
  6617. */
  6618. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  6619. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  6620. const b = color.mul( 12.92 );
  6621. const factor = color.lessThanEqual( 0.0031308 );
  6622. const rgbResult = mix( a, b, factor );
  6623. return rgbResult;
  6624. } ).setLayout( {
  6625. name: 'sRGBTransferOETF',
  6626. type: 'vec3',
  6627. inputs: [
  6628. { name: 'color', type: 'vec3' }
  6629. ]
  6630. } );
  6631. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  6632. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  6633. /**
  6634. * This node represents a color space conversion. Meaning it converts
  6635. * a color value from a source to a target color space.
  6636. *
  6637. * @augments TempNode
  6638. */
  6639. class ColorSpaceNode extends TempNode {
  6640. static get type() {
  6641. return 'ColorSpaceNode';
  6642. }
  6643. /**
  6644. * Constructs a new color space node.
  6645. *
  6646. * @param {Node} colorNode - Represents the color to convert.
  6647. * @param {string} source - The source color space.
  6648. * @param {string} target - The target color space.
  6649. */
  6650. constructor( colorNode, source, target ) {
  6651. super( 'vec4' );
  6652. /**
  6653. * Represents the color to convert.
  6654. *
  6655. * @type {Node}
  6656. */
  6657. this.colorNode = colorNode;
  6658. /**
  6659. * The source color space.
  6660. *
  6661. * @type {string}
  6662. */
  6663. this.source = source;
  6664. /**
  6665. * The target color space.
  6666. *
  6667. * @type {string}
  6668. */
  6669. this.target = target;
  6670. }
  6671. /**
  6672. * This method resolves the constants `WORKING_COLOR_SPACE` and
  6673. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  6674. * color management and renderer.
  6675. *
  6676. * @param {NodeBuilder} builder - The current node builder.
  6677. * @param {string} colorSpace - The color space to resolve.
  6678. * @return {string} The resolved color space.
  6679. */
  6680. resolveColorSpace( builder, colorSpace ) {
  6681. if ( colorSpace === WORKING_COLOR_SPACE ) {
  6682. return ColorManagement.workingColorSpace;
  6683. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  6684. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  6685. }
  6686. return colorSpace;
  6687. }
  6688. setup( builder ) {
  6689. const { colorNode } = this;
  6690. const source = this.resolveColorSpace( builder, this.source );
  6691. const target = this.resolveColorSpace( builder, this.target );
  6692. let outputNode = colorNode;
  6693. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  6694. return outputNode;
  6695. }
  6696. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  6697. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  6698. }
  6699. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  6700. outputNode = vec4(
  6701. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  6702. outputNode.a
  6703. );
  6704. }
  6705. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  6706. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  6707. }
  6708. return outputNode;
  6709. }
  6710. }
  6711. /**
  6712. * TSL function for converting a given color node from the current working color space to the given color space.
  6713. *
  6714. * @tsl
  6715. * @function
  6716. * @param {Node} node - Represents the node to convert.
  6717. * @param {string} targetColorSpace - The target color space.
  6718. * @returns {ColorSpaceNode}
  6719. */
  6720. const workingToColorSpace = ( node, targetColorSpace ) => new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, targetColorSpace );
  6721. /**
  6722. * TSL function for converting a given color node from the given color space to the current working color space.
  6723. *
  6724. * @tsl
  6725. * @function
  6726. * @param {Node} node - Represents the node to convert.
  6727. * @param {string} sourceColorSpace - The source color space.
  6728. * @returns {ColorSpaceNode}
  6729. */
  6730. const colorSpaceToWorking = ( node, sourceColorSpace ) => new ColorSpaceNode( nodeObject( node ), sourceColorSpace, WORKING_COLOR_SPACE );
  6731. /**
  6732. * TSL function for converting a given color node from one color space to another one.
  6733. *
  6734. * @tsl
  6735. * @function
  6736. * @param {Node} node - Represents the node to convert.
  6737. * @param {string} sourceColorSpace - The source color space.
  6738. * @param {string} targetColorSpace - The target color space.
  6739. * @returns {ColorSpaceNode}
  6740. */
  6741. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace );
  6742. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  6743. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  6744. // TODO: Avoid duplicated code and use only ReferenceBaseNode or ReferenceNode
  6745. /**
  6746. * This class is only relevant if the referenced property is array-like.
  6747. * In this case, `ReferenceElementNode` allows to refer to a specific
  6748. * element inside the data structure via an index.
  6749. *
  6750. * @augments ArrayElementNode
  6751. */
  6752. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  6753. static get type() {
  6754. return 'ReferenceElementNode';
  6755. }
  6756. /**
  6757. * Constructs a new reference element node.
  6758. *
  6759. * @param {ReferenceBaseNode} referenceNode - The reference node.
  6760. * @param {Node} indexNode - The index node that defines the element access.
  6761. */
  6762. constructor( referenceNode, indexNode ) {
  6763. super( referenceNode, indexNode );
  6764. /**
  6765. * Similar to {@link ReferenceBaseNode#reference}, an additional
  6766. * property references to the current node.
  6767. *
  6768. * @type {?ReferenceBaseNode}
  6769. * @default null
  6770. */
  6771. this.referenceNode = referenceNode;
  6772. /**
  6773. * This flag can be used for type testing.
  6774. *
  6775. * @type {boolean}
  6776. * @readonly
  6777. * @default true
  6778. */
  6779. this.isReferenceElementNode = true;
  6780. }
  6781. /**
  6782. * This method is overwritten since the node type is inferred from
  6783. * the uniform type of the reference node.
  6784. *
  6785. * @return {string} The node type.
  6786. */
  6787. generateNodeType() {
  6788. return this.referenceNode.uniformType;
  6789. }
  6790. generate( builder ) {
  6791. const snippet = super.generate( builder );
  6792. const arrayType = this.referenceNode.getNodeType();
  6793. const elementType = this.getNodeType();
  6794. return builder.format( snippet, arrayType, elementType );
  6795. }
  6796. };
  6797. /**
  6798. * Base class for nodes which establishes a reference to a property of another object.
  6799. * In this way, the value of the node is automatically linked to the value of
  6800. * referenced object. Reference nodes internally represent the linked value
  6801. * as a uniform.
  6802. *
  6803. * @augments Node
  6804. */
  6805. class ReferenceBaseNode extends Node {
  6806. static get type() {
  6807. return 'ReferenceBaseNode';
  6808. }
  6809. /**
  6810. * Constructs a new reference base node.
  6811. *
  6812. * @param {string} property - The name of the property the node refers to.
  6813. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  6814. * @param {?Object} [object=null] - The object the property belongs to.
  6815. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  6816. */
  6817. constructor( property, uniformType, object = null, count = null ) {
  6818. super();
  6819. /**
  6820. * The name of the property the node refers to.
  6821. *
  6822. * @type {string}
  6823. */
  6824. this.property = property;
  6825. /**
  6826. * The uniform type that should be used to represent the property value.
  6827. *
  6828. * @type {string}
  6829. */
  6830. this.uniformType = uniformType;
  6831. /**
  6832. * The object the property belongs to.
  6833. *
  6834. * @type {?Object}
  6835. * @default null
  6836. */
  6837. this.object = object;
  6838. /**
  6839. * When the linked property is an array, this parameter defines its length.
  6840. *
  6841. * @type {?number}
  6842. * @default null
  6843. */
  6844. this.count = count;
  6845. /**
  6846. * The property name might have dots so nested properties can be referred.
  6847. * The hierarchy of the names is stored inside this array.
  6848. *
  6849. * @type {Array<string>}
  6850. */
  6851. this.properties = property.split( '.' );
  6852. /**
  6853. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  6854. * since the final reference might be updated from calling code.
  6855. *
  6856. * @type {?Object}
  6857. * @default null
  6858. */
  6859. this.reference = object;
  6860. /**
  6861. * The uniform node that holds the value of the reference node.
  6862. *
  6863. * @type {UniformNode}
  6864. * @default null
  6865. */
  6866. this.node = null;
  6867. /**
  6868. * The uniform group of the internal uniform.
  6869. *
  6870. * @type {UniformGroupNode}
  6871. * @default null
  6872. */
  6873. this.group = null;
  6874. /**
  6875. * Overwritten since reference nodes are updated per object.
  6876. *
  6877. * @type {string}
  6878. * @default 'object'
  6879. */
  6880. this.updateType = NodeUpdateType.OBJECT;
  6881. }
  6882. /**
  6883. * Sets the uniform group for this reference node.
  6884. *
  6885. * @param {UniformGroupNode} group - The uniform group to set.
  6886. * @return {ReferenceBaseNode} A reference to this node.
  6887. */
  6888. setGroup( group ) {
  6889. this.group = group;
  6890. return this;
  6891. }
  6892. /**
  6893. * When the referred property is array-like, this method can be used
  6894. * to access elements via an index node.
  6895. *
  6896. * @param {IndexNode} indexNode - indexNode.
  6897. * @return {ReferenceElementNode} A reference to an element.
  6898. */
  6899. element( indexNode ) {
  6900. return new ReferenceElementNode$1( this, nodeObject( indexNode ) );
  6901. }
  6902. /**
  6903. * Sets the node type which automatically defines the internal
  6904. * uniform type.
  6905. *
  6906. * @param {string} uniformType - The type to set.
  6907. */
  6908. setNodeType( uniformType ) {
  6909. const node = uniform( null, uniformType );
  6910. if ( this.group !== null ) {
  6911. node.setGroup( this.group );
  6912. }
  6913. this.node = node;
  6914. }
  6915. /**
  6916. * This method is overwritten since the node type is inferred from
  6917. * the type of the reference node.
  6918. *
  6919. * @param {NodeBuilder} builder - The current node builder.
  6920. * @return {string} The node type.
  6921. */
  6922. generateNodeType( builder ) {
  6923. if ( this.node === null ) {
  6924. this.updateReference( builder );
  6925. this.updateValue();
  6926. }
  6927. return this.node.getNodeType( builder );
  6928. }
  6929. /**
  6930. * Returns the property value from the given referred object.
  6931. *
  6932. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  6933. * @return {any} The value.
  6934. */
  6935. getValueFromReference( object = this.reference ) {
  6936. const { properties } = this;
  6937. let value = object[ properties[ 0 ] ];
  6938. for ( let i = 1; i < properties.length; i ++ ) {
  6939. value = value[ properties[ i ] ];
  6940. }
  6941. return value;
  6942. }
  6943. /**
  6944. * Allows to update the reference based on the given state. The state is only
  6945. * evaluated {@link ReferenceBaseNode#object} is not set.
  6946. *
  6947. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6948. * @return {Object} The updated reference.
  6949. */
  6950. updateReference( state ) {
  6951. this.reference = this.object !== null ? this.object : state.object;
  6952. return this.reference;
  6953. }
  6954. /**
  6955. * The output of the reference node is the internal uniform node.
  6956. *
  6957. * @return {UniformNode} The output node.
  6958. */
  6959. setup() {
  6960. this.updateValue();
  6961. return this.node;
  6962. }
  6963. /**
  6964. * Overwritten to update the internal uniform value.
  6965. *
  6966. * @param {NodeFrame} frame - A reference to the current node frame.
  6967. */
  6968. update( /*frame*/ ) {
  6969. this.updateValue();
  6970. }
  6971. /**
  6972. * Retrieves the value from the referred object property and uses it
  6973. * to updated the internal uniform.
  6974. */
  6975. updateValue() {
  6976. if ( this.node === null ) this.setNodeType( this.uniformType );
  6977. const value = this.getValueFromReference();
  6978. if ( Array.isArray( value ) ) {
  6979. this.node.array = value;
  6980. } else {
  6981. this.node.value = value;
  6982. }
  6983. }
  6984. }
  6985. /**
  6986. * TSL function for creating a reference base node.
  6987. *
  6988. * @tsl
  6989. * @function
  6990. * @param {string} name - The name of the property the node refers to.
  6991. * @param {string} type - The uniform type that should be used to represent the property value.
  6992. * @param {Object} object - The object the property belongs to.
  6993. * @returns {ReferenceBaseNode}
  6994. */
  6995. const reference$1 = ( name, type, object ) => new ReferenceBaseNode( name, type, object );
  6996. /**
  6997. * This node is a special type of reference node which is intended
  6998. * for linking renderer properties with node values.
  6999. * ```js
  7000. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  7001. * ```
  7002. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  7003. * automatically be updated.
  7004. *
  7005. * @augments ReferenceBaseNode
  7006. */
  7007. class RendererReferenceNode extends ReferenceBaseNode {
  7008. static get type() {
  7009. return 'RendererReferenceNode';
  7010. }
  7011. /**
  7012. * Constructs a new renderer reference node.
  7013. *
  7014. * @param {string} property - The name of the property the node refers to.
  7015. * @param {string} inputType - The uniform type that should be used to represent the property value.
  7016. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  7017. * the node refers to the renderer of the current state.
  7018. */
  7019. constructor( property, inputType, renderer = null ) {
  7020. super( property, inputType, renderer );
  7021. /**
  7022. * The renderer the property belongs to. When no renderer is set,
  7023. * the node refers to the renderer of the current state.
  7024. *
  7025. * @type {?Renderer}
  7026. * @default null
  7027. */
  7028. this.renderer = renderer;
  7029. this.setGroup( renderGroup );
  7030. }
  7031. /**
  7032. * Updates the reference based on the given state. The state is only evaluated
  7033. * {@link RendererReferenceNode#renderer} is not set.
  7034. *
  7035. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  7036. * @return {Object} The updated reference.
  7037. */
  7038. updateReference( state ) {
  7039. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  7040. return this.reference;
  7041. }
  7042. }
  7043. /**
  7044. * TSL function for creating a renderer reference node.
  7045. *
  7046. * @tsl
  7047. * @function
  7048. * @param {string} name - The name of the property the node refers to.
  7049. * @param {string} type - The uniform type that should be used to represent the property value.
  7050. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  7051. * the node refers to the renderer of the current state.
  7052. * @returns {RendererReferenceNode}
  7053. */
  7054. const rendererReference = ( name, type, renderer = null ) => new RendererReferenceNode( name, type, renderer );
  7055. /**
  7056. * This node represents a tone mapping operation.
  7057. *
  7058. * @augments TempNode
  7059. */
  7060. class ToneMappingNode extends TempNode {
  7061. static get type() {
  7062. return 'ToneMappingNode';
  7063. }
  7064. /**
  7065. * Constructs a new tone mapping node.
  7066. *
  7067. * @param {number} toneMapping - The tone mapping type.
  7068. * @param {Node} exposureNode - The tone mapping exposure.
  7069. * @param {Node} [colorNode=null] - The color node to process.
  7070. */
  7071. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  7072. super( 'vec3' );
  7073. /**
  7074. * The tone mapping type.
  7075. *
  7076. * @private
  7077. * @type {number}
  7078. */
  7079. this._toneMapping = toneMapping;
  7080. /**
  7081. * The tone mapping exposure.
  7082. *
  7083. * @type {Node}
  7084. * @default null
  7085. */
  7086. this.exposureNode = exposureNode;
  7087. /**
  7088. * Represents the color to process.
  7089. *
  7090. * @type {?Node}
  7091. * @default null
  7092. */
  7093. this.colorNode = colorNode;
  7094. }
  7095. /**
  7096. * Overwrites the default `customCacheKey()` implementation by including the tone
  7097. * mapping type into the cache key.
  7098. *
  7099. * @return {number} The hash.
  7100. */
  7101. customCacheKey() {
  7102. return hash$1( this._toneMapping );
  7103. }
  7104. /**
  7105. * Sets the tone mapping type.
  7106. *
  7107. * @param {number} value - The tone mapping type.
  7108. * @return {ToneMappingNode} A reference to this node.
  7109. */
  7110. setToneMapping( value ) {
  7111. this._toneMapping = value;
  7112. return this;
  7113. }
  7114. /**
  7115. * Gets the tone mapping type.
  7116. *
  7117. * @returns {number} The tone mapping type.
  7118. */
  7119. getToneMapping() {
  7120. return this._toneMapping;
  7121. }
  7122. setup( builder ) {
  7123. const colorNode = this.colorNode || builder.context.color;
  7124. const toneMapping = this._toneMapping;
  7125. if ( toneMapping === NoToneMapping ) return colorNode;
  7126. let outputNode = null;
  7127. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  7128. if ( toneMappingFn !== null ) {
  7129. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  7130. } else {
  7131. error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  7132. outputNode = colorNode;
  7133. }
  7134. return outputNode;
  7135. }
  7136. }
  7137. /**
  7138. * TSL function for creating a tone mapping node.
  7139. *
  7140. * @tsl
  7141. * @function
  7142. * @param {number} mapping - The tone mapping type.
  7143. * @param {Node<float> | number} exposure - The tone mapping exposure.
  7144. * @param {Node<vec3> | Color} color - The color node to process.
  7145. * @returns {ToneMappingNode<vec3>}
  7146. */
  7147. const toneMapping = ( mapping, exposure, color ) => new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) );
  7148. /**
  7149. * TSL object that represents the global tone mapping exposure of the renderer.
  7150. *
  7151. * @tsl
  7152. * @type {RendererReferenceNode<vec3>}
  7153. */
  7154. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  7155. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  7156. /**
  7157. * Internal buffer attribute library.
  7158. *
  7159. * @private
  7160. * @type {WeakMap<TypedArray, InterleavedBuffer>}
  7161. */
  7162. const _bufferLib = new WeakMap();
  7163. /**
  7164. * Internal method for retrieving or creating interleaved buffers.
  7165. *
  7166. * @private
  7167. * @param {TypedArray} value - The attribute data.
  7168. * @param {number} itemSize - The attribute item size.
  7169. * @returns {InterleavedBuffer} The interleaved buffer.
  7170. */
  7171. function _getBufferAttribute( value, itemSize ) {
  7172. let buffer = _bufferLib.get( value );
  7173. if ( buffer === undefined ) {
  7174. buffer = new InterleavedBuffer( value, itemSize );
  7175. _bufferLib.set( value, buffer );
  7176. }
  7177. return buffer;
  7178. }
  7179. /**
  7180. * In earlier `three.js` versions it was only possible to define attribute data
  7181. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  7182. * on the node level.
  7183. * ```js
  7184. * const geometry = new THREE.PlaneGeometry();
  7185. * const positionAttribute = geometry.getAttribute( 'position' );
  7186. *
  7187. * const colors = [];
  7188. * for ( let i = 0; i < position.count; i ++ ) {
  7189. * colors.push( 1, 0, 0 );
  7190. * }
  7191. *
  7192. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  7193. * ```
  7194. * This new approach is especially interesting when geometry data are generated via
  7195. * compute shaders. The below line converts a storage buffer into an attribute node.
  7196. * ```js
  7197. * material.positionNode = positionBuffer.toAttribute();
  7198. * ```
  7199. * @augments InputNode
  7200. */
  7201. class BufferAttributeNode extends InputNode {
  7202. static get type() {
  7203. return 'BufferAttributeNode';
  7204. }
  7205. /**
  7206. * Constructs a new buffer attribute node.
  7207. *
  7208. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  7209. * @param {?string} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  7210. * @param {number} [bufferStride=0] - The buffer stride.
  7211. * @param {number} [bufferOffset=0] - The buffer offset.
  7212. */
  7213. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  7214. super( value, bufferType );
  7215. /**
  7216. * This flag can be used for type testing.
  7217. *
  7218. * @type {boolean}
  7219. * @readonly
  7220. * @default true
  7221. */
  7222. this.isBufferNode = true;
  7223. /**
  7224. * The buffer type (e.g. `'vec3'`).
  7225. *
  7226. * @type {?string}
  7227. * @default null
  7228. */
  7229. this.bufferType = bufferType;
  7230. /**
  7231. * The buffer stride.
  7232. *
  7233. * @type {number}
  7234. * @default 0
  7235. */
  7236. this.bufferStride = bufferStride;
  7237. /**
  7238. * The buffer offset.
  7239. *
  7240. * @type {number}
  7241. * @default 0
  7242. */
  7243. this.bufferOffset = bufferOffset;
  7244. /**
  7245. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  7246. * if you are planning to update the attribute data per frame.
  7247. *
  7248. * @type {number}
  7249. * @default StaticDrawUsage
  7250. */
  7251. this.usage = StaticDrawUsage;
  7252. /**
  7253. * Whether the attribute is instanced or not.
  7254. *
  7255. * @type {boolean}
  7256. * @default false
  7257. */
  7258. this.instanced = false;
  7259. /**
  7260. * A reference to the buffer attribute.
  7261. *
  7262. * @type {?BufferAttribute}
  7263. * @default null
  7264. */
  7265. this.attribute = null;
  7266. /**
  7267. * `BufferAttributeNode` sets this property to `true` by default.
  7268. *
  7269. * @type {boolean}
  7270. * @default true
  7271. */
  7272. this.global = true;
  7273. if ( value && value.isBufferAttribute === true && value.itemSize <= 4 ) {
  7274. this.attribute = value;
  7275. this.usage = value.usage;
  7276. this.instanced = value.isInstancedBufferAttribute;
  7277. }
  7278. }
  7279. /**
  7280. * This method is overwritten since the attribute data might be shared
  7281. * and thus the hash should be shared as well.
  7282. *
  7283. * @param {NodeBuilder} builder - The current node builder.
  7284. * @return {string} The hash.
  7285. */
  7286. getHash( builder ) {
  7287. let id;
  7288. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  7289. let bufferData = builder.globalCache.getData( this.value );
  7290. if ( bufferData === undefined ) {
  7291. bufferData = {
  7292. node: this
  7293. };
  7294. builder.globalCache.setData( this.value, bufferData );
  7295. }
  7296. id = bufferData.node.id;
  7297. } else {
  7298. id = this.id;
  7299. }
  7300. return String( id );
  7301. }
  7302. /**
  7303. * This method is overwritten since the node type is inferred from
  7304. * the buffer attribute.
  7305. *
  7306. * @param {NodeBuilder} builder - The current node builder.
  7307. * @return {string} The node type.
  7308. */
  7309. generateNodeType( builder ) {
  7310. if ( this.bufferType === null ) {
  7311. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  7312. }
  7313. return this.bufferType;
  7314. }
  7315. /**
  7316. * Depending on which value was passed to the node, `setup()` behaves
  7317. * differently. If no instance of `BufferAttribute` was passed, the method
  7318. * creates an internal attribute and configures it respectively.
  7319. *
  7320. * @param {NodeBuilder} builder - The current node builder.
  7321. */
  7322. setup( builder ) {
  7323. if ( this.attribute !== null ) return;
  7324. //
  7325. const type = this.getNodeType( builder );
  7326. const itemSize = builder.getTypeLength( type );
  7327. const value = this.value;
  7328. const stride = this.bufferStride || itemSize;
  7329. const offset = this.bufferOffset;
  7330. let buffer;
  7331. if ( value.isInterleavedBuffer === true ) {
  7332. buffer = value;
  7333. } else if ( value.isBufferAttribute === true ) {
  7334. buffer = _getBufferAttribute( value.array, stride );
  7335. } else {
  7336. buffer = _getBufferAttribute( value, stride );
  7337. }
  7338. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  7339. buffer.setUsage( this.usage );
  7340. this.attribute = bufferAttribute;
  7341. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  7342. }
  7343. /**
  7344. * Generates the code snippet of the buffer attribute node.
  7345. *
  7346. * @param {NodeBuilder} builder - The current node builder.
  7347. * @return {string} The generated code snippet.
  7348. */
  7349. generate( builder ) {
  7350. const nodeType = this.getNodeType( builder );
  7351. const nodeName = builder.context.nodeName;
  7352. if ( nodeName !== undefined ) delete builder.context.nodeName; // deleting when consumed
  7353. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType, nodeName );
  7354. const propertyName = builder.getPropertyName( nodeAttribute );
  7355. let output = null;
  7356. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  7357. this.name = propertyName;
  7358. output = propertyName;
  7359. } else {
  7360. let varyingName;
  7361. if ( nodeName ) {
  7362. varyingName = nodeName + 'Varying';
  7363. }
  7364. const nodeVarying = varying( this, varyingName );
  7365. output = nodeVarying.build( builder, nodeType );
  7366. }
  7367. return output;
  7368. }
  7369. /**
  7370. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  7371. *
  7372. * @param {NodeBuilder} builder - The current node builder.
  7373. * @return {string} The input type.
  7374. */
  7375. getInputType( /*builder*/ ) {
  7376. return 'bufferAttribute';
  7377. }
  7378. /**
  7379. * Sets the `usage` property to the given value.
  7380. *
  7381. * @param {number} value - The usage to set.
  7382. * @return {BufferAttributeNode} A reference to this node.
  7383. */
  7384. setUsage( value ) {
  7385. this.usage = value;
  7386. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  7387. this.attribute.usage = value;
  7388. }
  7389. return this;
  7390. }
  7391. /**
  7392. * Sets the `instanced` property to the given value.
  7393. *
  7394. * @param {boolean} value - The value to set.
  7395. * @return {BufferAttributeNode} A reference to this node.
  7396. */
  7397. setInstanced( value ) {
  7398. this.instanced = value;
  7399. return this;
  7400. }
  7401. }
  7402. /**
  7403. * Internal method for creating buffer attribute nodes.
  7404. *
  7405. * @private
  7406. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  7407. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  7408. * @param {number} [stride=0] - The buffer stride.
  7409. * @param {number} [offset=0] - The buffer offset.
  7410. * @param {number} [usage=StaticDrawUsage] - The buffer usage.
  7411. * @param {boolean} [instanced=false] - Whether the buffer is instanced.
  7412. * @returns {BufferAttributeNode|Node} The buffer attribute node.
  7413. */
  7414. function createBufferAttribute( array, type = null, stride = 0, offset = 0, usage = StaticDrawUsage, instanced = false ) {
  7415. if ( type === 'mat3' || ( type === null && array.itemSize === 9 ) ) {
  7416. return mat3(
  7417. new BufferAttributeNode( array, 'vec3', 9, 0 ).setUsage( usage ).setInstanced( instanced ),
  7418. new BufferAttributeNode( array, 'vec3', 9, 3 ).setUsage( usage ).setInstanced( instanced ),
  7419. new BufferAttributeNode( array, 'vec3', 9, 6 ).setUsage( usage ).setInstanced( instanced )
  7420. );
  7421. } else if ( type === 'mat4' || ( type === null && array.itemSize === 16 ) ) {
  7422. return mat4(
  7423. new BufferAttributeNode( array, 'vec4', 16, 0 ).setUsage( usage ).setInstanced( instanced ),
  7424. new BufferAttributeNode( array, 'vec4', 16, 4 ).setUsage( usage ).setInstanced( instanced ),
  7425. new BufferAttributeNode( array, 'vec4', 16, 8 ).setUsage( usage ).setInstanced( instanced ),
  7426. new BufferAttributeNode( array, 'vec4', 16, 12 ).setUsage( usage ).setInstanced( instanced )
  7427. );
  7428. }
  7429. return new BufferAttributeNode( array, type, stride, offset ).setUsage( usage );
  7430. }
  7431. /**
  7432. * TSL function for creating a buffer attribute node.
  7433. *
  7434. * @tsl
  7435. * @function
  7436. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  7437. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  7438. * @param {number} [stride=0] - The buffer stride.
  7439. * @param {number} [offset=0] - The buffer offset.
  7440. * @returns {BufferAttributeNode|Node}
  7441. */
  7442. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset );
  7443. /**
  7444. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  7445. * Use this function if attribute data are updated per frame.
  7446. *
  7447. * @tsl
  7448. * @function
  7449. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  7450. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  7451. * @param {number} [stride=0] - The buffer stride.
  7452. * @param {number} [offset=0] - The buffer offset.
  7453. * @returns {BufferAttributeNode|Node}
  7454. */
  7455. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, DynamicDrawUsage );
  7456. /**
  7457. * TSL function for creating a buffer attribute node but with enabled instancing
  7458. *
  7459. * @tsl
  7460. * @function
  7461. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  7462. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  7463. * @param {number} [stride=0] - The buffer stride.
  7464. * @param {number} [offset=0] - The buffer offset.
  7465. * @returns {BufferAttributeNode|Node}
  7466. */
  7467. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, StaticDrawUsage, true );
  7468. /**
  7469. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  7470. *
  7471. * @tsl
  7472. * @function
  7473. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  7474. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  7475. * @param {number} [stride=0] - The buffer stride.
  7476. * @param {number} [offset=0] - The buffer offset.
  7477. * @returns {BufferAttributeNode|Node}
  7478. */
  7479. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, DynamicDrawUsage, true );
  7480. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  7481. /**
  7482. * This class represents shader indices of different types. The following predefined node
  7483. * objects cover frequent use cases:
  7484. *
  7485. * - `vertexIndex`: The index of a vertex within a mesh.
  7486. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  7487. * - `drawIndex`: The index of a draw call.
  7488. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  7489. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  7490. * - `subgroupIndex`: The index of a compute invocation's subgroup within its workgroup.
  7491. *
  7492. * @augments Node
  7493. */
  7494. class IndexNode extends Node {
  7495. static get type() {
  7496. return 'IndexNode';
  7497. }
  7498. /**
  7499. * Constructs a new index node.
  7500. *
  7501. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationGlobal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  7502. */
  7503. constructor( scope ) {
  7504. super( 'uint' );
  7505. /**
  7506. * The scope of the index node.
  7507. *
  7508. * @type {string}
  7509. */
  7510. this.scope = scope;
  7511. /**
  7512. * This flag can be used for type testing.
  7513. *
  7514. * @type {boolean}
  7515. * @readonly
  7516. * @default true
  7517. */
  7518. this.isIndexNode = true;
  7519. }
  7520. generate( builder ) {
  7521. const nodeType = this.getNodeType( builder );
  7522. const scope = this.scope;
  7523. let propertyName;
  7524. if ( scope === IndexNode.VERTEX ) {
  7525. propertyName = builder.getVertexIndex();
  7526. } else if ( scope === IndexNode.INSTANCE ) {
  7527. propertyName = builder.getInstanceIndex();
  7528. } else if ( scope === IndexNode.DRAW ) {
  7529. propertyName = builder.getDrawIndex();
  7530. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  7531. propertyName = builder.getInvocationLocalIndex();
  7532. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  7533. propertyName = builder.getInvocationSubgroupIndex();
  7534. } else if ( scope === IndexNode.SUBGROUP ) {
  7535. propertyName = builder.getSubgroupIndex();
  7536. } else {
  7537. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  7538. }
  7539. let output;
  7540. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  7541. output = propertyName;
  7542. } else {
  7543. const nodeVarying = varying( this );
  7544. output = nodeVarying.build( builder, nodeType );
  7545. }
  7546. return output;
  7547. }
  7548. }
  7549. IndexNode.VERTEX = 'vertex';
  7550. IndexNode.INSTANCE = 'instance';
  7551. IndexNode.SUBGROUP = 'subgroup';
  7552. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  7553. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  7554. IndexNode.DRAW = 'draw';
  7555. /**
  7556. * TSL object that represents the index of a vertex within a mesh.
  7557. *
  7558. * @tsl
  7559. * @type {IndexNode}
  7560. */
  7561. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  7562. /**
  7563. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  7564. *
  7565. * @tsl
  7566. * @type {IndexNode}
  7567. */
  7568. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  7569. /**
  7570. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  7571. *
  7572. * @tsl
  7573. * @type {IndexNode}
  7574. */
  7575. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  7576. /**
  7577. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  7578. *
  7579. * @tsl
  7580. * @type {IndexNode}
  7581. */
  7582. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  7583. /**
  7584. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  7585. *
  7586. * @tsl
  7587. * @type {IndexNode}
  7588. */
  7589. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  7590. /**
  7591. * TSL object that represents the index of a draw call.
  7592. *
  7593. * @tsl
  7594. * @type {IndexNode}
  7595. */
  7596. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  7597. /**
  7598. * Represents a compute shader node.
  7599. *
  7600. * @augments Node
  7601. */
  7602. class ComputeNode extends Node {
  7603. static get type() {
  7604. return 'ComputeNode';
  7605. }
  7606. /**
  7607. * Constructs a new compute node.
  7608. *
  7609. * @param {Node} computeNode - The node that defines the compute shader logic.
  7610. * @param {Array<number>} workgroupSize - An array defining the X, Y, and Z dimensions of the workgroup for compute shader execution.
  7611. */
  7612. constructor( computeNode, workgroupSize ) {
  7613. super( 'void' );
  7614. /**
  7615. * This flag can be used for type testing.
  7616. *
  7617. * @type {boolean}
  7618. * @readonly
  7619. * @default true
  7620. */
  7621. this.isComputeNode = true;
  7622. /**
  7623. * The node that defines the compute shader logic.
  7624. *
  7625. * @type {Node}
  7626. */
  7627. this.computeNode = computeNode;
  7628. /**
  7629. * An array defining the X, Y, and Z dimensions of the workgroup for compute shader execution.
  7630. *
  7631. * @type {Array<number>}
  7632. * @default [ 64 ]
  7633. */
  7634. this.workgroupSize = workgroupSize;
  7635. /**
  7636. * The total number of threads (invocations) to execute. If it is a number, it will be used
  7637. * to automatically generate bounds checking against `instanceIndex`.
  7638. *
  7639. * @type {number|Array<number>}
  7640. */
  7641. this.count = null;
  7642. /**
  7643. * The dispatch size for workgroups on X, Y, and Z axes.
  7644. * Used directly if `count` is not provided.
  7645. *
  7646. * @type {number|Array<number>}
  7647. */
  7648. this.dispatchSize = null;
  7649. /**
  7650. * The version of the node.
  7651. *
  7652. * @type {number}
  7653. */
  7654. this.version = 1;
  7655. /**
  7656. * The name or label of the uniform.
  7657. *
  7658. * @type {string}
  7659. * @default ''
  7660. */
  7661. this.name = '';
  7662. /**
  7663. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  7664. * is executed once per object by default.
  7665. *
  7666. * @type {string}
  7667. * @default 'object'
  7668. */
  7669. this.updateBeforeType = NodeUpdateType.OBJECT;
  7670. /**
  7671. * A callback executed when the compute node finishes initialization.
  7672. *
  7673. * @type {?Function}
  7674. */
  7675. this.onInitFunction = null;
  7676. /**
  7677. * A uniform node holding the dispatch count for bounds checking.
  7678. * Created automatically when `count` is a number.
  7679. *
  7680. * @type {?UniformNode}
  7681. */
  7682. this.countNode = null;
  7683. }
  7684. /**
  7685. * Executes the `dispose` event for this node.
  7686. */
  7687. dispose() {
  7688. this.dispatchEvent( { type: 'dispose' } );
  7689. }
  7690. /**
  7691. * Sets the {@link ComputeNode#name} property.
  7692. *
  7693. * @param {string} name - The name of the uniform.
  7694. * @return {ComputeNode} A reference to this node.
  7695. */
  7696. setName( name ) {
  7697. this.name = name;
  7698. return this;
  7699. }
  7700. /**
  7701. * Sets the {@link ComputeNode#name} property.
  7702. *
  7703. * @deprecated
  7704. * @param {string} name - The name of the uniform.
  7705. * @return {ComputeNode} A reference to this node.
  7706. */
  7707. label( name ) {
  7708. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.', new StackTrace() ); // @deprecated r179
  7709. return this.setName( name );
  7710. }
  7711. /**
  7712. * Sets the callback to run during initialization.
  7713. *
  7714. * @param {Function} callback - The callback function.
  7715. * @return {ComputeNode} A reference to this node.
  7716. */
  7717. onInit( callback ) {
  7718. this.onInitFunction = callback;
  7719. return this;
  7720. }
  7721. /**
  7722. * The method execute the compute for this node.
  7723. *
  7724. * @param {NodeFrame} frame - A reference to the current node frame.
  7725. */
  7726. updateBefore( { renderer } ) {
  7727. renderer.compute( this );
  7728. }
  7729. setup( builder ) {
  7730. if ( this.count !== null && this.countNode === null ) {
  7731. this.countNode = uniform( this.count, 'uint' ).onObjectUpdate( () => this.count );
  7732. }
  7733. const result = this.computeNode.build( builder );
  7734. if ( result ) {
  7735. const properties = builder.getNodeProperties( this );
  7736. properties.outputComputeNode = result.outputNode;
  7737. result.outputNode = null;
  7738. }
  7739. return result;
  7740. }
  7741. generate( builder, output ) {
  7742. const { shaderStage } = builder;
  7743. if ( shaderStage === 'compute' ) {
  7744. const snippet = this.computeNode.build( builder, 'void' );
  7745. if ( snippet !== '' ) {
  7746. builder.addLineFlowCode( snippet, this );
  7747. }
  7748. if ( this.count !== null && builder.allowEarlyReturns === true ) {
  7749. const countSnippet = this.countNode.build( builder, 'uint' );
  7750. const indexSnippet = instanceIndex.build( builder, 'uint' );
  7751. builder.flow.code = `${ builder.tab }if ( ${ indexSnippet } >= ${ countSnippet } ) { return; }\n\n${ builder.flow.code }`;
  7752. }
  7753. } else {
  7754. const properties = builder.getNodeProperties( this );
  7755. const outputComputeNode = properties.outputComputeNode;
  7756. if ( outputComputeNode ) {
  7757. return outputComputeNode.build( builder, output );
  7758. }
  7759. }
  7760. }
  7761. }
  7762. /**
  7763. * TSL function for creating a compute kernel node.
  7764. *
  7765. * @tsl
  7766. * @function
  7767. * @param {Node} node - The TSL logic for the compute shader.
  7768. * @param {Array<number>} [workgroupSize=[64]] - The workgroup size.
  7769. * @returns {ComputeNode}
  7770. */
  7771. const computeKernel = ( node, workgroupSize = [ 64 ] ) => {
  7772. if ( workgroupSize.length === 0 || workgroupSize.length > 3 ) {
  7773. error( 'TSL: compute() workgroupSize must have 1, 2, or 3 elements', new StackTrace() );
  7774. }
  7775. for ( let i = 0; i < workgroupSize.length; i ++ ) {
  7776. const val = workgroupSize[ i ];
  7777. if ( typeof val !== 'number' || val <= 0 || ! Number.isInteger( val ) ) {
  7778. error( `TSL: compute() workgroupSize element at index [ ${ i } ] must be a positive integer`, new StackTrace() );
  7779. }
  7780. }
  7781. // Implicit fill-up to [ x, y, z ] with 1s, just like WGSL treats @workgroup_size when fewer dimensions are specified
  7782. while ( workgroupSize.length < 3 ) workgroupSize.push( 1 );
  7783. //
  7784. return new ComputeNode( nodeObject( node ), workgroupSize );
  7785. };
  7786. /**
  7787. * TSL function for creating a compute node.
  7788. *
  7789. * @tsl
  7790. * @function
  7791. * @param {Node} node - The TSL logic for the compute shader.
  7792. * @param {number|Array<number>} count - The compute count or dispatch size.
  7793. * @param {Array<number>} [workgroupSize=[64]] - The workgroup size.
  7794. * @returns {ComputeNode}
  7795. , */
  7796. const compute = ( node, count, workgroupSize ) => {
  7797. const computeNode = computeKernel( node, workgroupSize );
  7798. if ( typeof count === 'number' ) {
  7799. computeNode.count = count;
  7800. } else {
  7801. computeNode.dispatchSize = count;
  7802. }
  7803. return computeNode;
  7804. };
  7805. addMethodChaining( 'compute', compute );
  7806. addMethodChaining( 'computeKernel', computeKernel );
  7807. /**
  7808. * This node can be used as a cache management component for another node.
  7809. * Caching is in general used by default in {@link NodeBuilder} but this node
  7810. * allows the usage of a shared parent cache during the build process.
  7811. *
  7812. * @augments Node
  7813. */
  7814. class IsolateNode extends Node {
  7815. static get type() {
  7816. return 'IsolateNode';
  7817. }
  7818. /**
  7819. * Constructs a new cache node.
  7820. *
  7821. * @param {Node} node - The node that should be cached.
  7822. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  7823. */
  7824. constructor( node, parent = true ) {
  7825. super();
  7826. /**
  7827. * The node that should be cached.
  7828. *
  7829. * @type {Node}
  7830. */
  7831. this.node = node;
  7832. /**
  7833. * Whether this node refers to a shared parent cache or not.
  7834. *
  7835. * @type {boolean}
  7836. * @default true
  7837. */
  7838. this.parent = parent;
  7839. /**
  7840. * This flag can be used for type testing.
  7841. *
  7842. * @type {boolean}
  7843. * @readonly
  7844. * @default true
  7845. */
  7846. this.isIsolateNode = true;
  7847. }
  7848. generateNodeType( builder ) {
  7849. const previousCache = builder.getCache();
  7850. const cache = builder.getCacheFromNode( this, this.parent );
  7851. builder.setCache( cache );
  7852. const nodeType = this.node.getNodeType( builder );
  7853. builder.setCache( previousCache );
  7854. return nodeType;
  7855. }
  7856. build( builder, ...params ) {
  7857. const previousCache = builder.getCache();
  7858. const cache = builder.getCacheFromNode( this, this.parent );
  7859. builder.setCache( cache );
  7860. const data = this.node.build( builder, ...params );
  7861. builder.setCache( previousCache );
  7862. return data;
  7863. }
  7864. setParent( parent ) {
  7865. this.parent = parent;
  7866. return this;
  7867. }
  7868. getParent() {
  7869. return this.parent;
  7870. }
  7871. }
  7872. /**
  7873. * TSL function for creating a cache node.
  7874. *
  7875. * @tsl
  7876. * @function
  7877. * @param {Node} node - The node that should be cached.
  7878. * @returns {IsolateNode}
  7879. */
  7880. const isolate = ( node ) => new IsolateNode( nodeObject( node ) );
  7881. /**
  7882. * TSL function for creating a cache node.
  7883. *
  7884. * @tsl
  7885. * @function
  7886. * @deprecated
  7887. * @param {Node} node - The node that should be cached.
  7888. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  7889. * @returns {IsolateNode}
  7890. */
  7891. function cache( node, parent = true ) {
  7892. warn( 'TSL: "cache()" has been deprecated. Use "isolate()" instead.' ); // @deprecated r181
  7893. return isolate( node ).setParent( parent );
  7894. }
  7895. addMethodChaining( 'cache', cache );
  7896. addMethodChaining( 'isolate', isolate );
  7897. /**
  7898. * The class generates the code of a given node but returns another node in the output.
  7899. * This can be used to call a method or node that does not return a value, i.e.
  7900. * type `void` on an input where returning a value is required. Example:
  7901. *
  7902. * ```js
  7903. * material.colorNode = myColor.bypass( runVoidFn() )
  7904. *```
  7905. *
  7906. * @augments Node
  7907. */
  7908. class BypassNode extends Node {
  7909. static get type() {
  7910. return 'BypassNode';
  7911. }
  7912. /**
  7913. * Constructs a new bypass node.
  7914. *
  7915. * @param {Node} outputNode - The output node.
  7916. * @param {Node} callNode - The call node.
  7917. */
  7918. constructor( outputNode, callNode ) {
  7919. super();
  7920. /**
  7921. * This flag can be used for type testing.
  7922. *
  7923. * @type {boolean}
  7924. * @readonly
  7925. * @default true
  7926. */
  7927. this.isBypassNode = true;
  7928. /**
  7929. * The output node.
  7930. *
  7931. * @type {Node}
  7932. */
  7933. this.outputNode = outputNode;
  7934. /**
  7935. * The call node.
  7936. *
  7937. * @type {Node}
  7938. */
  7939. this.callNode = callNode;
  7940. }
  7941. generateNodeType( builder ) {
  7942. return this.outputNode.getNodeType( builder );
  7943. }
  7944. generate( builder ) {
  7945. const snippet = this.callNode.build( builder, 'void' );
  7946. if ( snippet !== '' ) {
  7947. builder.addLineFlowCode( snippet, this );
  7948. }
  7949. return this.outputNode.build( builder );
  7950. }
  7951. }
  7952. /**
  7953. * TSL function for creating a bypass node.
  7954. *
  7955. * @tsl
  7956. * @function
  7957. * @param {Node} outputNode - The output node.
  7958. * @param {Node} callNode - The call node.
  7959. * @returns {BypassNode}
  7960. */
  7961. const bypass = /*@__PURE__*/ nodeProxy( BypassNode ).setParameterLength( 2 );
  7962. addMethodChaining( 'bypass', bypass );
  7963. /**
  7964. * This node allows to remap a node value from one range into another. E.g a value of
  7965. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  7966. * `remap` takes care of that and converts the original value of `0.4` to `0.5`.
  7967. *
  7968. * @tsl
  7969. * @function
  7970. * @param {Node} node - The node that should be remapped.
  7971. * @param {Node} inLowNode - The source or current lower bound of the range.
  7972. * @param {Node} inHighNode - The source or current upper bound of the range.
  7973. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7974. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7975. * @returns {Node}
  7976. */
  7977. const remap = /*@__PURE__*/ Fn( ( [ node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ), doClamp = bool( false ) ] ) => {
  7978. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  7979. if ( defined( doClamp ) ) t = t.clamp();
  7980. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  7981. } );
  7982. /**
  7983. * This node allows to remap a node value from one range into another but with enabled clamping. E.g a value of
  7984. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  7985. * `remapClamp` takes care of that and converts the original value of `0.4` to `0.5`.
  7986. *
  7987. * @tsl
  7988. * @function
  7989. * @param {Node} node - The node that should be remapped.
  7990. * @param {Node} inLowNode - The source or current lower bound of the range.
  7991. * @param {Node} inHighNode - The source or current upper bound of the range.
  7992. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7993. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7994. * @returns {Node}
  7995. */
  7996. function remapClamp( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  7997. return remap( node, inLowNode, inHighNode, outLowNode, outHighNode, true );
  7998. }
  7999. addMethodChaining( 'remap', remap );
  8000. addMethodChaining( 'remapClamp', remapClamp );
  8001. /**
  8002. * This class can be used to implement basic expressions in shader code.
  8003. * Basic examples for that are `return`, `continue` or `discard` statements.
  8004. *
  8005. * @augments Node
  8006. */
  8007. class ExpressionNode extends Node {
  8008. static get type() {
  8009. return 'ExpressionNode';
  8010. }
  8011. /**
  8012. * Constructs a new expression node.
  8013. *
  8014. * @param {string} [snippet=''] - The native code snippet.
  8015. * @param {string} [nodeType='void'] - The node type.
  8016. */
  8017. constructor( snippet = '', nodeType = 'void' ) {
  8018. super( nodeType );
  8019. /**
  8020. * The native code snippet.
  8021. *
  8022. * @type {string}
  8023. * @default ''
  8024. */
  8025. this.snippet = snippet;
  8026. }
  8027. generate( builder, output ) {
  8028. const type = this.getNodeType( builder );
  8029. const snippet = this.snippet;
  8030. if ( type === 'void' ) {
  8031. builder.addLineFlowCode( snippet, this );
  8032. } else {
  8033. return builder.format( snippet, type, output );
  8034. }
  8035. }
  8036. }
  8037. /**
  8038. * TSL function for creating an expression node.
  8039. *
  8040. * @tsl
  8041. * @function
  8042. * @param {string} [snippet] - The native code snippet.
  8043. * @param {?string} [nodeType='void'] - The node type.
  8044. * @returns {ExpressionNode}
  8045. */
  8046. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode ).setParameterLength( 1, 2 );
  8047. /**
  8048. * Represents a `discard` shader operation in TSL.
  8049. *
  8050. * @tsl
  8051. * @function
  8052. * @param {?ConditionalNode} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  8053. * @return {Node} The `discard` expression.
  8054. */
  8055. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).toStack();
  8056. /**
  8057. * Represents a `return` shader operation in TSL.
  8058. *
  8059. * @tsl
  8060. * @function
  8061. * @return {ExpressionNode} The `return` expression.
  8062. */
  8063. const Return = () => expression( 'return' ).toStack();
  8064. addMethodChaining( 'discard', Discard );
  8065. /**
  8066. * Premultiplies the RGB channels of a color by its alpha channel.
  8067. *
  8068. * This function is useful for converting a non-premultiplied alpha color
  8069. * into a premultiplied alpha format, where the RGB values are scaled
  8070. * by the alpha value. Premultiplied alpha is often used in graphics
  8071. * rendering for certain operations, such as compositing and image processing.
  8072. *
  8073. * @tsl
  8074. * @function
  8075. * @param {Node<vec4>} color - The input color with non-premultiplied alpha.
  8076. * @return {Node<vec4>} The color with premultiplied alpha.
  8077. */
  8078. const premultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  8079. return vec4( color.rgb.mul( color.a ), color.a );
  8080. }, { color: 'vec4', return: 'vec4' } );
  8081. /**
  8082. * Unpremultiplies the RGB channels of a color by its alpha channel.
  8083. *
  8084. * This function is useful for converting a premultiplied alpha color
  8085. * back into a non-premultiplied alpha format, where the RGB values are
  8086. * divided by the alpha value. Unpremultiplied alpha is often used in graphics
  8087. * rendering for certain operations, such as compositing and image processing.
  8088. *
  8089. * @tsl
  8090. * @function
  8091. * @param {Node<vec4>} color - The input color with premultiplied alpha.
  8092. * @return {Node<vec4>} The color with non-premultiplied alpha.
  8093. */
  8094. const unpremultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  8095. return color.a.equal( 0 ).select( vec4( 0 ), vec4( color.rgb.div( color.a ), color.a ) );
  8096. }, { color: 'vec4', return: 'vec4' } );
  8097. /**
  8098. * Normally, tone mapping and color conversion happens automatically just
  8099. * before outputting a pixel to the default (screen) framebuffer. In certain
  8100. * post processing setups this is too late because some effects such as FXAA
  8101. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  8102. * to apply tone mapping and color space conversion at an arbitrary point
  8103. * in the effect chain.
  8104. *
  8105. * When applying tone mapping and color space conversion manually with this node,
  8106. * you have to set {@link RenderPipeline#outputColorTransform} to `false`.
  8107. *
  8108. * ```js
  8109. * const postProcessing = new RenderPipeline( renderer );
  8110. * postProcessing.outputColorTransform = false;
  8111. *
  8112. * const scenePass = pass( scene, camera );
  8113. * const outputPass = renderOutput( scenePass );
  8114. *
  8115. * postProcessing.outputNode = outputPass;
  8116. * ```
  8117. *
  8118. * @augments TempNode
  8119. */
  8120. class RenderOutputNode extends TempNode {
  8121. static get type() {
  8122. return 'RenderOutputNode';
  8123. }
  8124. /**
  8125. * Constructs a new render output node.
  8126. *
  8127. * @param {Node} colorNode - The color node to process.
  8128. * @param {?number} toneMapping - The tone mapping type.
  8129. * @param {?string} outputColorSpace - The output color space.
  8130. */
  8131. constructor( colorNode, toneMapping, outputColorSpace ) {
  8132. super( 'vec4' );
  8133. /**
  8134. * The color node to process.
  8135. *
  8136. * @type {Node}
  8137. */
  8138. this.colorNode = colorNode;
  8139. /**
  8140. * The tone mapping type.
  8141. *
  8142. * @private
  8143. * @type {?number}
  8144. */
  8145. this._toneMapping = toneMapping;
  8146. /**
  8147. * The output color space.
  8148. *
  8149. * @type {?string}
  8150. */
  8151. this.outputColorSpace = outputColorSpace;
  8152. /**
  8153. * This flag can be used for type testing.
  8154. *
  8155. * @type {boolean}
  8156. * @readonly
  8157. * @default true
  8158. */
  8159. this.isRenderOutputNode = true;
  8160. }
  8161. /**
  8162. * Sets the tone mapping type.
  8163. *
  8164. * @param {number} value - The tone mapping type.
  8165. * @return {ToneMappingNode} A reference to this node.
  8166. */
  8167. setToneMapping( value ) {
  8168. this._toneMapping = value;
  8169. return this;
  8170. }
  8171. /**
  8172. * Gets the tone mapping type.
  8173. *
  8174. * @returns {number} The tone mapping type.
  8175. */
  8176. getToneMapping() {
  8177. return this._toneMapping;
  8178. }
  8179. setup( { context } ) {
  8180. let outputNode = this.colorNode || context.color;
  8181. // clamp alpha
  8182. outputNode = vec4( outputNode.rgb, outputNode.a.clamp( 0.0, 1.0 ) );
  8183. // unpremultiply
  8184. outputNode = unpremultiplyAlpha( outputNode );
  8185. // tone mapping
  8186. const toneMapping = ( this._toneMapping !== null ? this._toneMapping : context.toneMapping ) || NoToneMapping;
  8187. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  8188. if ( toneMapping !== NoToneMapping ) {
  8189. outputNode = outputNode.toneMapping( toneMapping );
  8190. }
  8191. // working to output color space
  8192. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  8193. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  8194. }
  8195. // premultiply in output color space
  8196. outputNode = premultiplyAlpha( outputNode );
  8197. return outputNode;
  8198. }
  8199. }
  8200. /**
  8201. * TSL function for creating a render output node.
  8202. *
  8203. * @tsl
  8204. * @function
  8205. * @param {Node} color - The color node to process.
  8206. * @param {?number} [toneMapping=null] - The tone mapping type.
  8207. * @param {?string} [outputColorSpace=null] - The output color space.
  8208. * @returns {RenderOutputNode}
  8209. */
  8210. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace );
  8211. addMethodChaining( 'renderOutput', renderOutput );
  8212. class DebugNode extends TempNode {
  8213. static get type() {
  8214. return 'DebugNode';
  8215. }
  8216. constructor( node, callback = null ) {
  8217. super();
  8218. this.node = node;
  8219. this.callback = callback;
  8220. }
  8221. generateNodeType( builder ) {
  8222. return this.node.getNodeType( builder );
  8223. }
  8224. setup( builder ) {
  8225. return this.node.build( builder );
  8226. }
  8227. analyze( builder ) {
  8228. return this.node.build( builder );
  8229. }
  8230. generate( builder ) {
  8231. const callback = this.callback;
  8232. const snippet = this.node.build( builder );
  8233. if ( callback !== null ) {
  8234. callback( builder, snippet );
  8235. } else {
  8236. const title = '--- TSL debug - ' + builder.shaderStage + ' shader ---';
  8237. const border = '-'.repeat( title.length );
  8238. let code = '';
  8239. code += '// #' + title + '#\n';
  8240. code += builder.flow.code.replace( /^\t/mg, '' ) + '\n';
  8241. code += '/* ... */ ' + snippet + ' /* ... */\n';
  8242. code += '// #' + border + '#\n';
  8243. log$1( code );
  8244. }
  8245. return snippet;
  8246. }
  8247. }
  8248. /**
  8249. * TSL function for creating a debug node.
  8250. *
  8251. * @tsl
  8252. * @function
  8253. * @param {Node} node - The node to debug.
  8254. * @param {?Function} [callback=null] - Optional callback function to handle the debug output.
  8255. * @returns {DebugNode}
  8256. */
  8257. const debug = ( node, callback = null ) => new DebugNode( nodeObject( node ), callback ).toStack();
  8258. addMethodChaining( 'debug', debug );
  8259. /**
  8260. * InspectorBase is the base class for all inspectors.
  8261. *
  8262. * @class InspectorBase
  8263. * @augments EventDispatcher
  8264. */
  8265. class InspectorBase extends EventDispatcher {
  8266. /**
  8267. * Creates a new InspectorBase.
  8268. */
  8269. constructor() {
  8270. super();
  8271. /**
  8272. * The renderer associated with this inspector.
  8273. *
  8274. * @type {WebGLRenderer}
  8275. * @private
  8276. */
  8277. this._renderer = null;
  8278. /**
  8279. * The current frame being processed.
  8280. *
  8281. * @type {Object}
  8282. */
  8283. this.currentFrame = null;
  8284. }
  8285. /**
  8286. * Returns the node frame for the current renderer.
  8287. *
  8288. * @return {Object} The node frame.
  8289. */
  8290. get nodeFrame() {
  8291. return this._renderer._nodes.nodeFrame;
  8292. }
  8293. /**
  8294. * Sets the renderer for this inspector.
  8295. *
  8296. * @param {WebGLRenderer} renderer - The renderer to associate with this inspector.
  8297. * @return {InspectorBase} This inspector instance.
  8298. */
  8299. setRenderer( renderer ) {
  8300. this._renderer = renderer;
  8301. return this;
  8302. }
  8303. /**
  8304. * Returns the renderer associated with this inspector.
  8305. *
  8306. * @return {WebGLRenderer} The associated renderer.
  8307. */
  8308. getRenderer() {
  8309. return this._renderer;
  8310. }
  8311. /**
  8312. * Initializes the inspector.
  8313. */
  8314. init() { }
  8315. /**
  8316. * Called when a frame begins.
  8317. */
  8318. begin() { }
  8319. /**
  8320. * Called when a frame ends.
  8321. */
  8322. finish() { }
  8323. /**
  8324. * Inspects a node.
  8325. *
  8326. * @param {Node} node - The node to inspect.
  8327. */
  8328. inspect( /*node*/ ) { }
  8329. /**
  8330. * When a compute operation is performed.
  8331. *
  8332. * @param {ComputeNode} computeNode - The compute node being executed.
  8333. * @param {number|Array<number>} dispatchSizeOrCount - The dispatch size or count.
  8334. */
  8335. computeAsync( /*computeNode, dispatchSizeOrCount*/ ) { }
  8336. /**
  8337. * Called when a compute operation begins.
  8338. *
  8339. * @param {string} uid - A unique identifier for the render context.
  8340. * @param {ComputeNode} computeNode - The compute node being executed.
  8341. */
  8342. beginCompute( /*uid, computeNode*/ ) { }
  8343. /**
  8344. * Called when a compute operation ends.
  8345. *
  8346. * @param {string} uid - A unique identifier for the render context.
  8347. * @param {ComputeNode} computeNode - The compute node being executed.
  8348. */
  8349. finishCompute( /*uid*/ ) { }
  8350. /**
  8351. * Called when a render operation begins.
  8352. *
  8353. * @param {string} uid - A unique identifier for the render context.
  8354. * @param {Scene} scene - The scene being rendered.
  8355. * @param {Camera} camera - The camera being used for rendering.
  8356. * @param {?WebGLRenderTarget} renderTarget - The render target, if any.
  8357. */
  8358. beginRender( /*uid, scene, camera, renderTarget*/ ) { }
  8359. /**
  8360. * Called when an animation loop ends.
  8361. *
  8362. * @param {string} uid - A unique identifier for the render context.
  8363. */
  8364. finishRender( /*uid*/ ) { }
  8365. /**
  8366. * Called when a texture copy operation is performed.
  8367. *
  8368. * @param {Texture} srcTexture - The source texture.
  8369. * @param {Texture} dstTexture - The destination texture.
  8370. */
  8371. copyTextureToTexture( /*srcTexture, dstTexture*/ ) { }
  8372. /**
  8373. * Called when a framebuffer copy operation is performed.
  8374. *
  8375. * @param {Texture} framebufferTexture - The texture associated with the framebuffer.
  8376. */
  8377. copyFramebufferToTexture( /*framebufferTexture*/ ) { }
  8378. }
  8379. /**
  8380. * InspectorNode is a wrapper node that allows inspection of node values during rendering.
  8381. * It can be used to debug or analyze node outputs in the rendering pipeline.
  8382. *
  8383. * @augments Node
  8384. */
  8385. class InspectorNode extends Node {
  8386. /**
  8387. * Returns the type of the node.
  8388. *
  8389. * @returns {string}
  8390. */
  8391. static get type() {
  8392. return 'InspectorNode';
  8393. }
  8394. /**
  8395. * Creates an InspectorNode.
  8396. *
  8397. * @param {Node} node - The node to inspect.
  8398. * @param {string} [name=''] - Optional name for the inspector node.
  8399. * @param {Function|null} [callback=null] - Optional callback to modify the node during setup.
  8400. */
  8401. constructor( node, name = '', callback = null ) {
  8402. super();
  8403. this.node = node;
  8404. this.name = name;
  8405. this.callback = callback;
  8406. this.updateType = NodeUpdateType.FRAME;
  8407. this.isInspectorNode = true;
  8408. }
  8409. /**
  8410. * Returns the name of the inspector node.
  8411. *
  8412. * @returns {string}
  8413. */
  8414. getName() {
  8415. return this.name || this.node.name;
  8416. }
  8417. /**
  8418. * Updates the inspector node, allowing inspection of the wrapped node.
  8419. *
  8420. * @param {NodeFrame} frame - A reference to the current node frame.
  8421. */
  8422. update( frame ) {
  8423. frame.renderer.inspector.inspect( this );
  8424. }
  8425. /**
  8426. * Returns the type of the wrapped node.
  8427. *
  8428. * @param {NodeBuilder} builder - The node builder.
  8429. * @returns {string}
  8430. */
  8431. generateNodeType( builder ) {
  8432. return this.node.getNodeType( builder );
  8433. }
  8434. /**
  8435. * Sets up the inspector node.
  8436. *
  8437. * @param {NodeBuilder} builder - The node builder.
  8438. * @returns {Node} The setup node.
  8439. */
  8440. setup( builder ) {
  8441. let node = this.node;
  8442. if ( builder.context.inspector === true && this.callback !== null ) {
  8443. node = this.callback( node );
  8444. }
  8445. if ( builder.renderer.backend.isWebGPUBackend !== true && builder.renderer.inspector.constructor !== InspectorBase ) {
  8446. warnOnce( 'TSL: ".toInspector()" is only available with WebGPU.' );
  8447. }
  8448. return node;
  8449. }
  8450. }
  8451. /**
  8452. * Creates an inspector node to wrap around a given node for inspection purposes.
  8453. *
  8454. * @tsl
  8455. * @param {Node} node - The node to inspect.
  8456. * @param {string} [name=''] - Optional name for the inspector node.
  8457. * @param {Function|null} [callback=null] - Optional callback to modify the node during setup.
  8458. * @returns {Node} The inspector node.
  8459. */
  8460. function inspector( node, name = '', callback = null ) {
  8461. node = nodeObject( node );
  8462. return node.before( new InspectorNode( node, name, callback ) );
  8463. }
  8464. addMethodChaining( 'toInspector', inspector );
  8465. function addNodeElement( name/*, nodeElement*/ ) {
  8466. warn( 'TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  8467. }
  8468. /**
  8469. * Base class for representing shader attributes as nodes.
  8470. *
  8471. * @augments Node
  8472. */
  8473. class AttributeNode extends Node {
  8474. static get type() {
  8475. return 'AttributeNode';
  8476. }
  8477. /**
  8478. * Constructs a new attribute node.
  8479. *
  8480. * @param {string} attributeName - The name of the attribute.
  8481. * @param {?string} nodeType - The node type.
  8482. */
  8483. constructor( attributeName, nodeType = null ) {
  8484. super( nodeType );
  8485. /**
  8486. * `AttributeNode` sets this property to `true` by default.
  8487. *
  8488. * @type {boolean}
  8489. * @default true
  8490. */
  8491. this.global = true;
  8492. this._attributeName = attributeName;
  8493. }
  8494. getHash( builder ) {
  8495. return this.getAttributeName( builder );
  8496. }
  8497. generateNodeType( builder ) {
  8498. let nodeType = this.nodeType;
  8499. if ( nodeType === null ) {
  8500. const attributeName = this.getAttributeName( builder );
  8501. if ( builder.hasGeometryAttribute( attributeName ) ) {
  8502. const attribute = builder.geometry.getAttribute( attributeName );
  8503. nodeType = builder.getTypeFromAttribute( attribute );
  8504. } else {
  8505. nodeType = 'float';
  8506. }
  8507. }
  8508. return nodeType;
  8509. }
  8510. /**
  8511. * Sets the attribute name to the given value. The method can be
  8512. * overwritten in derived classes if the final name must be computed
  8513. * analytically.
  8514. *
  8515. * @param {string} attributeName - The name of the attribute.
  8516. * @return {AttributeNode} A reference to this node.
  8517. */
  8518. setAttributeName( attributeName ) {
  8519. this._attributeName = attributeName;
  8520. return this;
  8521. }
  8522. /**
  8523. * Returns the attribute name of this node. The method can be
  8524. * overwritten in derived classes if the final name must be computed
  8525. * analytically.
  8526. *
  8527. * @param {NodeBuilder} builder - The current node builder.
  8528. * @return {string} The attribute name.
  8529. */
  8530. getAttributeName( /*builder*/ ) {
  8531. return this._attributeName;
  8532. }
  8533. generate( builder ) {
  8534. const attributeName = this.getAttributeName( builder );
  8535. const nodeType = this.getNodeType( builder );
  8536. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  8537. if ( geometryAttribute === true ) {
  8538. const attribute = builder.geometry.getAttribute( attributeName );
  8539. const attributeType = builder.getTypeFromAttribute( attribute );
  8540. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  8541. if ( builder.shaderStage === 'vertex' ) {
  8542. return builder.format( nodeAttribute.name, attributeType, nodeType );
  8543. } else {
  8544. const nodeVarying = varying( this );
  8545. return nodeVarying.build( builder, nodeType );
  8546. }
  8547. } else {
  8548. warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  8549. return builder.generateConst( nodeType );
  8550. }
  8551. }
  8552. serialize( data ) {
  8553. super.serialize( data );
  8554. data.global = this.global;
  8555. data._attributeName = this._attributeName;
  8556. }
  8557. deserialize( data ) {
  8558. super.deserialize( data );
  8559. this.global = data.global;
  8560. this._attributeName = data._attributeName;
  8561. }
  8562. }
  8563. /**
  8564. * TSL function for creating an attribute node.
  8565. *
  8566. * @tsl
  8567. * @function
  8568. * @param {string} name - The name of the attribute.
  8569. * @param {?string} [nodeType=null] - The node type.
  8570. * @returns {AttributeNode}
  8571. */
  8572. const attribute = ( name, nodeType = null ) => new AttributeNode( name, nodeType );
  8573. /**
  8574. * TSL function for creating an uv attribute node with the given index.
  8575. *
  8576. * @tsl
  8577. * @function
  8578. * @param {number} [index=0] - The uv index.
  8579. * @return {AttributeNode<vec2>} The uv attribute node.
  8580. */
  8581. const uv$1 = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  8582. /**
  8583. * A node that represents the dimensions of a texture. The texture size is
  8584. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  8585. * or `textureSize()`.
  8586. *
  8587. * @augments Node
  8588. */
  8589. class TextureSizeNode extends Node {
  8590. static get type() {
  8591. return 'TextureSizeNode';
  8592. }
  8593. /**
  8594. * Constructs a new texture size node.
  8595. *
  8596. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  8597. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  8598. */
  8599. constructor( textureNode, levelNode = null ) {
  8600. super( 'uvec2' );
  8601. /**
  8602. * This flag can be used for type testing.
  8603. *
  8604. * @type {boolean}
  8605. * @readonly
  8606. * @default true
  8607. */
  8608. this.isTextureSizeNode = true;
  8609. /**
  8610. * A texture node which size should be retrieved.
  8611. *
  8612. * @type {TextureNode}
  8613. */
  8614. this.textureNode = textureNode;
  8615. /**
  8616. * A level node which defines the requested mip.
  8617. *
  8618. * @type {Node<int>}
  8619. * @default null
  8620. */
  8621. this.levelNode = levelNode;
  8622. }
  8623. generate( builder ) {
  8624. const textureProperty = this.textureNode.build( builder, 'property' );
  8625. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  8626. const snippet = builder.generateTextureSize( this.textureNode.value, textureProperty, level );
  8627. return builder.format( snippet, this.getNodeType( builder ) );
  8628. }
  8629. }
  8630. /**
  8631. * TSL function for creating a texture size node.
  8632. *
  8633. * @tsl
  8634. * @function
  8635. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  8636. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  8637. * @returns {TextureSizeNode}
  8638. */
  8639. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode ).setParameterLength( 1, 2 );
  8640. /**
  8641. * A special type of uniform node that computes the
  8642. * maximum mipmap level for a given texture node.
  8643. *
  8644. * ```js
  8645. * const level = maxMipLevel( textureNode );
  8646. * ```
  8647. *
  8648. * @augments UniformNode
  8649. */
  8650. class MaxMipLevelNode extends UniformNode {
  8651. static get type() {
  8652. return 'MaxMipLevelNode';
  8653. }
  8654. /**
  8655. * Constructs a new max mip level node.
  8656. *
  8657. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  8658. */
  8659. constructor( textureNode ) {
  8660. super( 0 );
  8661. /**
  8662. * The texture node to compute the max mip level for.
  8663. *
  8664. * @private
  8665. * @type {TextureNode}
  8666. */
  8667. this._textureNode = textureNode;
  8668. /**
  8669. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  8670. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  8671. *
  8672. * @type {string}
  8673. * @default 'frame'
  8674. */
  8675. this.updateType = NodeUpdateType.FRAME;
  8676. }
  8677. /**
  8678. * The texture node to compute the max mip level for.
  8679. *
  8680. * @readonly
  8681. * @type {TextureNode}
  8682. */
  8683. get textureNode() {
  8684. return this._textureNode;
  8685. }
  8686. /**
  8687. * The texture.
  8688. *
  8689. * @readonly
  8690. * @type {Texture}
  8691. */
  8692. get texture() {
  8693. return this._textureNode.value;
  8694. }
  8695. update() {
  8696. const texture = this.texture;
  8697. const images = texture.images;
  8698. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  8699. if ( image && image.width !== undefined ) {
  8700. const { width, height } = image;
  8701. this.value = Math.log2( Math.max( width, height ) );
  8702. }
  8703. }
  8704. }
  8705. /**
  8706. * TSL function for creating a max mip level node.
  8707. *
  8708. * @tsl
  8709. * @function
  8710. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  8711. * @returns {MaxMipLevelNode}
  8712. */
  8713. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode ).setParameterLength( 1 );
  8714. /**
  8715. * Custom error class for node-related errors, including stack trace information.
  8716. */
  8717. class NodeError extends Error {
  8718. constructor( message, stackTrace = null ) {
  8719. super( message );
  8720. /**
  8721. * The name of the error.
  8722. *
  8723. * @type {string}
  8724. */
  8725. this.name = 'NodeError';
  8726. /**
  8727. * The stack trace associated with the error.
  8728. *
  8729. * @type {?StackTrace}
  8730. */
  8731. this.stackTrace = stackTrace;
  8732. }
  8733. }
  8734. const EmptyTexture$1 = /*@__PURE__*/ new Texture();
  8735. /**
  8736. * This type of uniform node represents a 2D texture.
  8737. *
  8738. * @augments UniformNode
  8739. */
  8740. class TextureNode extends UniformNode {
  8741. static get type() {
  8742. return 'TextureNode';
  8743. }
  8744. /**
  8745. * Constructs a new texture node.
  8746. *
  8747. * @param {Texture} [value=EmptyTexture] - The texture.
  8748. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8749. * @param {?Node<int>} [levelNode=null] - The level node.
  8750. * @param {?Node<float>} [biasNode=null] - The bias node.
  8751. */
  8752. constructor( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) {
  8753. super( value );
  8754. /**
  8755. * This flag can be used for type testing.
  8756. *
  8757. * @type {boolean}
  8758. * @readonly
  8759. * @default true
  8760. */
  8761. this.isTextureNode = true;
  8762. /**
  8763. * Represents the texture coordinates.
  8764. *
  8765. * @type {?Node<vec2|vec3>}
  8766. * @default null
  8767. */
  8768. this.uvNode = uvNode;
  8769. /**
  8770. * Represents the mip level that should be selected.
  8771. *
  8772. * @type {?Node<int>}
  8773. * @default null
  8774. */
  8775. this.levelNode = levelNode;
  8776. /**
  8777. * Represents the bias to be applied during level-of-detail computation.
  8778. *
  8779. * @type {?Node<float>}
  8780. * @default null
  8781. */
  8782. this.biasNode = biasNode;
  8783. /**
  8784. * Represents a reference value a texture sample is compared to.
  8785. *
  8786. * @type {?Node<float>}
  8787. * @default null
  8788. */
  8789. this.compareNode = null;
  8790. /**
  8791. * When using texture arrays, the depth node defines the layer to select.
  8792. *
  8793. * @type {?Node<int>}
  8794. * @default null
  8795. */
  8796. this.depthNode = null;
  8797. /**
  8798. * When defined, a texture is sampled using explicit gradients.
  8799. *
  8800. * @type {?Array<Node<vec2>>}
  8801. * @default null
  8802. */
  8803. this.gradNode = null;
  8804. /**
  8805. * Represents the optional index constant of the channel to gather.
  8806. * This must be in range [0, 3] and a compile-time constant.
  8807. *
  8808. * @type {?Node<int>}
  8809. * @default null
  8810. */
  8811. this.gatherNode = null;
  8812. /**
  8813. * Represents the optional texel offset applied to the unnormalized texture
  8814. * coordinate before sampling the texture.
  8815. *
  8816. * @type {?Node<ivec2|ivec3>}
  8817. * @default null
  8818. */
  8819. this.offsetNode = null;
  8820. /**
  8821. * Whether texture values should be sampled or fetched.
  8822. *
  8823. * @type {boolean}
  8824. * @default true
  8825. */
  8826. this.sampler = true;
  8827. /**
  8828. * Whether the uv transformation matrix should be
  8829. * automatically updated or not. Use `setUpdateMatrix()`
  8830. * if you want to change the value of the property.
  8831. *
  8832. * @type {boolean}
  8833. * @default false
  8834. */
  8835. this.updateMatrix = false;
  8836. /**
  8837. * By default the `update()` method is not executed. Depending on
  8838. * whether a uv transformation matrix and/or flipY is applied, `update()`
  8839. * is executed per object.
  8840. *
  8841. * @type {string}
  8842. * @default 'none'
  8843. */
  8844. this.updateType = NodeUpdateType.NONE;
  8845. /**
  8846. * The reference node.
  8847. *
  8848. * @type {?Node}
  8849. * @default null
  8850. */
  8851. this.referenceNode = null;
  8852. /**
  8853. * The texture value is stored in a private property.
  8854. *
  8855. * @private
  8856. * @type {Texture}
  8857. */
  8858. this._value = value;
  8859. /**
  8860. * The uniform node that represents the uv transformation matrix.
  8861. *
  8862. * @private
  8863. * @type {?UniformNode<mat3>}
  8864. * @default null
  8865. */
  8866. this._matrixUniform = null;
  8867. /**
  8868. * The uniform node that represents the y-flip. Only required for WebGL.
  8869. *
  8870. * @private
  8871. * @type {?UniformNode<bool>}
  8872. * @default null
  8873. */
  8874. this._flipYUniform = null;
  8875. this.setUpdateMatrix( uvNode === null );
  8876. }
  8877. set value( value ) {
  8878. if ( this.referenceNode ) {
  8879. this.referenceNode.value = value;
  8880. } else {
  8881. this._value = value;
  8882. }
  8883. }
  8884. /**
  8885. * The texture value.
  8886. *
  8887. * @type {Texture}
  8888. */
  8889. get value() {
  8890. return this.referenceNode ? this.referenceNode.value : this._value;
  8891. }
  8892. /**
  8893. * Overwritten since the uniform hash is defined by the texture's UUID.
  8894. *
  8895. * @param {NodeBuilder} builder - The current node builder.
  8896. * @return {string} The uniform hash.
  8897. */
  8898. getUniformHash( /*builder*/ ) {
  8899. return this.value.uuid;
  8900. }
  8901. /**
  8902. * Overwritten since the node type is inferred from the texture type.
  8903. *
  8904. * @param {NodeBuilder} builder - The current node builder.
  8905. * @return {string} The node type.
  8906. */
  8907. generateNodeType( /*builder*/ ) {
  8908. if ( this.gatherNode !== null ) {
  8909. return 'vec4';
  8910. }
  8911. return getTextureType( this.value );
  8912. }
  8913. /**
  8914. * Overwrites the default implementation to return a fixed value `'texture'`.
  8915. *
  8916. * @param {NodeBuilder} builder - The current node builder.
  8917. * @return {string} The input type.
  8918. */
  8919. getInputType( /*builder*/ ) {
  8920. return 'texture';
  8921. }
  8922. /**
  8923. * Returns a default uvs based on the current texture's channel.
  8924. *
  8925. * @return {AttributeNode<vec2>} The default uvs.
  8926. */
  8927. getDefaultUV() {
  8928. return uv$1( this.value.channel );
  8929. }
  8930. /**
  8931. * Overwritten to always return the texture reference of the node.
  8932. *
  8933. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  8934. * @return {Texture} The texture reference.
  8935. */
  8936. updateReference( /*state*/ ) {
  8937. return this.value;
  8938. }
  8939. /**
  8940. * Transforms the given uv node with the texture transformation matrix.
  8941. *
  8942. * @param {Node} uvNode - The uv node to transform.
  8943. * @return {Node} The transformed uv node.
  8944. */
  8945. getTransformedUV( uvNode ) {
  8946. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  8947. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  8948. }
  8949. /**
  8950. * Defines whether the uv transformation matrix should automatically be updated or not.
  8951. *
  8952. * @param {boolean} value - The update toggle.
  8953. * @return {TextureNode} A reference to this node.
  8954. */
  8955. setUpdateMatrix( value ) {
  8956. this.updateMatrix = value;
  8957. return this;
  8958. }
  8959. /**
  8960. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  8961. * to modify the uv node for correct sampling.
  8962. *
  8963. * @param {NodeBuilder} builder - The current node builder.
  8964. * @param {Node} uvNode - The uv node to setup.
  8965. * @return {Node} The updated uv node.
  8966. */
  8967. setupUV( builder, uvNode ) {
  8968. if ( builder.isFlipY() ) {
  8969. if ( this._flipYUniform === null ) this._flipYUniform = uniform( false );
  8970. uvNode = uvNode.toVar();
  8971. if ( this.sampler ) {
  8972. uvNode = this._flipYUniform.select( uvNode.flipY(), uvNode );
  8973. } else {
  8974. uvNode = this._flipYUniform.select( uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) ), uvNode );
  8975. }
  8976. }
  8977. return uvNode;
  8978. }
  8979. /**
  8980. * Setups texture node by preparing the internal nodes for code generation.
  8981. *
  8982. * @param {NodeBuilder} builder - The current node builder.
  8983. */
  8984. setup( builder ) {
  8985. const properties = builder.getNodeProperties( this );
  8986. properties.referenceNode = this.referenceNode;
  8987. //
  8988. const texture = this.value;
  8989. if ( ! texture || texture.isTexture !== true ) {
  8990. throw new NodeError( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().', this.stackTrace );
  8991. }
  8992. //
  8993. const uvNode = Fn( () => {
  8994. let uvNode = this.uvNode;
  8995. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  8996. uvNode = builder.context.getUV( this, builder );
  8997. }
  8998. if ( ! uvNode ) uvNode = this.getDefaultUV();
  8999. if ( this.updateMatrix === true ) {
  9000. uvNode = this.getTransformedUV( uvNode );
  9001. }
  9002. uvNode = this.setupUV( builder, uvNode );
  9003. //
  9004. this.updateType = ( this._matrixUniform !== null || this._flipYUniform !== null ) ? NodeUpdateType.OBJECT : NodeUpdateType.NONE;
  9005. //
  9006. return uvNode;
  9007. } )();
  9008. //
  9009. let levelNode = this.levelNode;
  9010. if ( levelNode === null && builder.context.getTextureLevel ) {
  9011. levelNode = builder.context.getTextureLevel( this );
  9012. }
  9013. //
  9014. let compareNode = null;
  9015. let compareStepNode = null;
  9016. if ( this.compareNode !== null ) {
  9017. if ( builder.renderer.hasCompatibility( Compatibility.TEXTURE_COMPARE ) ) {
  9018. compareNode = this.compareNode;
  9019. } else {
  9020. const compareFunction = texture.compareFunction;
  9021. if ( compareFunction === null || compareFunction === LessCompare || compareFunction === LessEqualCompare || compareFunction === GreaterCompare || compareFunction === GreaterEqualCompare ) {
  9022. compareStepNode = this.compareNode;
  9023. } else {
  9024. compareNode = this.compareNode;
  9025. warnOnce( 'TSL: Only "LessCompare", "LessEqualCompare", "GreaterCompare" and "GreaterEqualCompare" are supported for depth texture comparison fallback.' );
  9026. }
  9027. }
  9028. }
  9029. properties.uvNode = uvNode;
  9030. properties.levelNode = levelNode;
  9031. properties.biasNode = this.biasNode;
  9032. properties.compareNode = compareNode;
  9033. properties.compareStepNode = compareStepNode;
  9034. properties.gradNode = this.gradNode;
  9035. properties.gatherNode = this.gatherNode;
  9036. properties.depthNode = this.depthNode;
  9037. properties.offsetNode = this.offsetNode;
  9038. }
  9039. /**
  9040. * Generates the uv code snippet.
  9041. *
  9042. * @param {NodeBuilder} builder - The current node builder.
  9043. * @param {Node} uvNode - The uv node to generate code for.
  9044. * @return {string} The generated code snippet.
  9045. */
  9046. generateUV( builder, uvNode ) {
  9047. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  9048. }
  9049. /**
  9050. * Generates the offset code snippet.
  9051. *
  9052. * @param {NodeBuilder} builder - The current node builder.
  9053. * @param {Node} offsetNode - The offset node to generate code for.
  9054. * @return {string} The generated code snippet.
  9055. */
  9056. generateOffset( builder, offsetNode ) {
  9057. return offsetNode.build( builder, 'ivec2' );
  9058. }
  9059. /**
  9060. * Generates the snippet for the texture sampling.
  9061. *
  9062. * @param {NodeBuilder} builder - The current node builder.
  9063. * @param {string} textureProperty - The texture property.
  9064. * @param {string} uvSnippet - The uv snippet.
  9065. * @param {?string} levelSnippet - The level snippet.
  9066. * @param {?string} biasSnippet - The bias snippet.
  9067. * @param {?string} depthSnippet - The depth snippet.
  9068. * @param {?string} compareSnippet - The compare snippet.
  9069. * @param {?Array<string>} gradSnippet - The grad snippet.
  9070. * @param {?string} gatherSnippet - The gather snippet.
  9071. * @param {?string} offsetSnippet - The offset snippet.
  9072. * @param {?string} flipYSnippet - The y-flip snippet. Only used for WebGL.
  9073. * @return {string} The generated code snippet.
  9074. */
  9075. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, gatherSnippet, offsetSnippet, flipYSnippet ) {
  9076. const texture = this.value;
  9077. let snippet;
  9078. if ( biasSnippet ) {
  9079. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet );
  9080. } else if ( gradSnippet ) {
  9081. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet );
  9082. } else if ( gatherSnippet ) {
  9083. if ( compareSnippet ) {
  9084. snippet = builder.generateTextureGatherCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, flipYSnippet );
  9085. } else {
  9086. snippet = builder.generateTextureGather( texture, textureProperty, uvSnippet, gatherSnippet, depthSnippet, offsetSnippet, flipYSnippet );
  9087. }
  9088. } else if ( compareSnippet ) {
  9089. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet );
  9090. } else if ( this.sampler === false ) {
  9091. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  9092. } else if ( levelSnippet ) {
  9093. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  9094. } else {
  9095. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet );
  9096. }
  9097. return snippet;
  9098. }
  9099. /**
  9100. * Generates the code snippet of the texture node.
  9101. *
  9102. * @param {NodeBuilder} builder - The current node builder.
  9103. * @param {string} output - The current output.
  9104. * @return {string} The generated code snippet.
  9105. */
  9106. generate( builder, output ) {
  9107. const texture = this.value;
  9108. const properties = builder.getNodeProperties( this );
  9109. const textureProperty = super.generate( builder, 'property' );
  9110. if ( /^sampler/.test( output ) ) {
  9111. return textureProperty + '_sampler';
  9112. } else if ( builder.isReference( output ) ) {
  9113. return textureProperty;
  9114. } else {
  9115. const nodeData = builder.getDataFromNode( this );
  9116. const nodeType = this.getNodeType( builder );
  9117. let propertyName = nodeData.propertyName;
  9118. if ( propertyName === undefined ) {
  9119. const { uvNode, levelNode, biasNode, compareNode, compareStepNode, depthNode, gradNode, gatherNode, offsetNode } = properties;
  9120. const uvSnippet = this.generateUV( builder, uvNode );
  9121. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  9122. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  9123. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  9124. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  9125. const compareStepSnippet = compareStepNode ? compareStepNode.build( builder, 'float' ) : null;
  9126. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  9127. const gatherSnippet = gatherNode ? gatherNode.build( builder, 'int' ) : null;
  9128. const offsetSnippet = offsetNode ? this.generateOffset( builder, offsetNode ) : null;
  9129. const flipYSnippet = this._flipYUniform ? this._flipYUniform.build( builder, 'bool' ) : null;
  9130. let finalDepthSnippet = depthSnippet;
  9131. if ( finalDepthSnippet === null && texture.isArrayTexture && this.isTexture3DNode !== true ) {
  9132. finalDepthSnippet = '0';
  9133. }
  9134. const nodeVar = builder.getVarFromNode( this );
  9135. propertyName = builder.getPropertyName( nodeVar );
  9136. let snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, finalDepthSnippet, compareSnippet, gradSnippet, gatherSnippet, offsetSnippet, flipYSnippet );
  9137. let snippetType;
  9138. if ( texture.isDepthTexture === true && gatherSnippet === null ) {
  9139. snippetType = 'float';
  9140. } else {
  9141. snippetType = texture.type === UnsignedIntType ? 'uvec4' : ( texture.type === IntType ? 'ivec4' : 'vec4' );
  9142. }
  9143. snippet = builder.format( snippet, snippetType, nodeType );
  9144. if ( compareStepSnippet !== null ) {
  9145. const compareFunction = texture.compareFunction;
  9146. if ( compareFunction === GreaterCompare || compareFunction === GreaterEqualCompare ) {
  9147. snippet = step( expression( snippet, nodeType ), expression( compareStepSnippet, 'float' ) ).build( builder, nodeType );
  9148. } else {
  9149. snippet = step( expression( compareStepSnippet, 'float' ), expression( snippet, nodeType ) ).build( builder, nodeType );
  9150. }
  9151. }
  9152. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  9153. nodeData.snippet = snippet;
  9154. nodeData.propertyName = propertyName;
  9155. }
  9156. let snippet = propertyName;
  9157. if ( builder.needsToWorkingColorSpace( texture ) ) {
  9158. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  9159. }
  9160. return builder.format( snippet, nodeType, output );
  9161. }
  9162. }
  9163. /**
  9164. * Sets the sampler value.
  9165. *
  9166. * @param {boolean} value - The sampler value to set.
  9167. * @return {TextureNode} A reference to this texture node.
  9168. */
  9169. setSampler( value ) {
  9170. this.sampler = value;
  9171. return this;
  9172. }
  9173. /**
  9174. * Returns the sampler value.
  9175. *
  9176. * @return {boolean} The sampler value.
  9177. */
  9178. getSampler() {
  9179. return this.sampler;
  9180. }
  9181. // @TODO: Move to TSL
  9182. /**
  9183. * Samples the texture with the given uv node.
  9184. *
  9185. * @param {Node} uvNode - The uv node.
  9186. * @return {TextureNode} A texture node representing the texture sample.
  9187. */
  9188. sample( uvNode ) {
  9189. const textureNode = this.clone();
  9190. textureNode.uvNode = nodeObject( uvNode );
  9191. textureNode.referenceNode = this.getBase();
  9192. return nodeObject( textureNode );
  9193. }
  9194. /**
  9195. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  9196. *
  9197. * @param {Node<uvec2>} uvNode - The uv node.
  9198. * @returns {TextureNode} A texture node representing the texture load.
  9199. */
  9200. load( uvNode ) {
  9201. return this.sample( uvNode ).setSampler( false );
  9202. }
  9203. /**
  9204. * Samples a blurred version of the texture by defining an internal bias.
  9205. *
  9206. * @param {Node<float>} amountNode - How blurred the texture should be.
  9207. * @return {TextureNode} A texture node representing the texture sample.
  9208. */
  9209. blur( amountNode ) {
  9210. const textureNode = this.clone();
  9211. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  9212. textureNode.referenceNode = this.getBase();
  9213. const map = textureNode.value;
  9214. if ( textureNode.generateMipmaps === false && ( map && map.generateMipmaps === false || map.minFilter === NearestFilter || map.magFilter === NearestFilter ) ) {
  9215. warn( 'TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture.' );
  9216. textureNode.biasNode = null;
  9217. }
  9218. return nodeObject( textureNode );
  9219. }
  9220. /**
  9221. * Samples a specific mip of the texture.
  9222. *
  9223. * @param {Node<int>} levelNode - The mip level to sample.
  9224. * @return {TextureNode} A texture node representing the texture sample.
  9225. */
  9226. level( levelNode ) {
  9227. const textureNode = this.clone();
  9228. textureNode.levelNode = nodeObject( levelNode );
  9229. textureNode.referenceNode = this.getBase();
  9230. return nodeObject( textureNode );
  9231. }
  9232. /**
  9233. * Returns the texture size of the requested level.
  9234. *
  9235. * @param {Node<int>} levelNode - The level to compute the size for.
  9236. * @return {TextureSizeNode} The texture size.
  9237. */
  9238. size( levelNode ) {
  9239. return textureSize( this, levelNode );
  9240. }
  9241. /**
  9242. * Samples the texture with the given bias.
  9243. *
  9244. * @param {Node<float>} biasNode - The bias node.
  9245. * @return {TextureNode} A texture node representing the texture sample.
  9246. */
  9247. bias( biasNode ) {
  9248. const textureNode = this.clone();
  9249. textureNode.biasNode = nodeObject( biasNode );
  9250. textureNode.referenceNode = this.getBase();
  9251. return nodeObject( textureNode );
  9252. }
  9253. /**
  9254. * Returns the base texture of this node.
  9255. * @return {TextureNode} The base texture node.
  9256. */
  9257. getBase() {
  9258. return this.referenceNode ? this.referenceNode.getBase() : this;
  9259. }
  9260. /**
  9261. * Samples the texture by executing a compare operation.
  9262. *
  9263. * @param {Node<float>} compareNode - The node that defines the compare value.
  9264. * @return {TextureNode} A texture node representing the texture sample.
  9265. */
  9266. compare( compareNode ) {
  9267. const textureNode = this.clone();
  9268. textureNode.compareNode = nodeObject( compareNode );
  9269. textureNode.referenceNode = this.getBase();
  9270. return nodeObject( textureNode );
  9271. }
  9272. /**
  9273. * Samples the texture using an explicit gradient.
  9274. *
  9275. * @param {Node<vec2>} gradNodeX - The gradX node.
  9276. * @param {Node<vec2>} gradNodeY - The gradY node.
  9277. * @return {TextureNode} A texture node representing the texture sample.
  9278. */
  9279. grad( gradNodeX, gradNodeY ) {
  9280. const textureNode = this.clone();
  9281. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  9282. textureNode.referenceNode = this.getBase();
  9283. return nodeObject( textureNode );
  9284. }
  9285. /**
  9286. * Gathers four texels from the texture.
  9287. *
  9288. * @param {Node<int>} gatherNode - The index of the channel to read. This must be in range [0, 3] and a compile-time constant.
  9289. * @return {TextureNode} A texture node representing the texture sample.
  9290. */
  9291. gather( gatherNode = 0 ) {
  9292. const textureNode = this.clone();
  9293. textureNode.gatherNode = nodeObject( gatherNode );
  9294. textureNode.referenceNode = this.getBase();
  9295. return nodeObject( textureNode );
  9296. }
  9297. /**
  9298. * Samples the texture by defining a depth node.
  9299. *
  9300. * @param {Node<int>} depthNode - The depth node.
  9301. * @return {TextureNode} A texture node representing the texture sample.
  9302. */
  9303. depth( depthNode ) {
  9304. const textureNode = this.clone();
  9305. textureNode.depthNode = nodeObject( depthNode );
  9306. textureNode.referenceNode = this.getBase();
  9307. return nodeObject( textureNode );
  9308. }
  9309. /**
  9310. * Samples the texture by defining an offset node.
  9311. *
  9312. * @param {Node<ivec2>} offsetNode - The offset node.
  9313. * @return {TextureNode} A texture node representing the texture sample.
  9314. */
  9315. offset( offsetNode ) {
  9316. const textureNode = this.clone();
  9317. textureNode.offsetNode = nodeObject( offsetNode );
  9318. textureNode.referenceNode = this.getBase();
  9319. return nodeObject( textureNode );
  9320. }
  9321. // --
  9322. serialize( data ) {
  9323. super.serialize( data );
  9324. data.value = this.value.toJSON( data.meta ).uuid;
  9325. data.sampler = this.sampler;
  9326. data.updateMatrix = this.updateMatrix;
  9327. data.updateType = this.updateType;
  9328. }
  9329. deserialize( data ) {
  9330. super.deserialize( data );
  9331. this.value = data.meta.textures[ data.value ];
  9332. this.sampler = data.sampler;
  9333. this.updateMatrix = data.updateMatrix;
  9334. this.updateType = data.updateType;
  9335. }
  9336. /**
  9337. * The update is used to implement the update of the uv transformation matrix.
  9338. */
  9339. update() {
  9340. const texture = this.value;
  9341. const matrixUniform = this._matrixUniform;
  9342. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  9343. if ( texture.matrixAutoUpdate === true ) {
  9344. texture.updateMatrix();
  9345. }
  9346. //
  9347. const flipYUniform = this._flipYUniform;
  9348. if ( flipYUniform !== null ) {
  9349. flipYUniform.value = ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true );
  9350. }
  9351. }
  9352. /**
  9353. * Clones the texture node.
  9354. *
  9355. * @return {TextureNode} The cloned texture node.
  9356. */
  9357. clone() {
  9358. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  9359. newNode.sampler = this.sampler;
  9360. newNode.depthNode = this.depthNode;
  9361. newNode.compareNode = this.compareNode;
  9362. newNode.gradNode = this.gradNode;
  9363. newNode.gatherNode = this.gatherNode;
  9364. newNode.offsetNode = this.offsetNode;
  9365. return newNode;
  9366. }
  9367. }
  9368. /**
  9369. * TSL function for creating a texture node.
  9370. *
  9371. * @tsl
  9372. * @function
  9373. * @param {?Texture} value - The texture.
  9374. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  9375. * @param {?Node<int>} [levelNode=null] - The level node.
  9376. * @param {?Node<float>} [biasNode=null] - The bias node.
  9377. * @returns {TextureNode}
  9378. */
  9379. const textureBase = /*@__PURE__*/ nodeProxy( TextureNode ).setParameterLength( 1, 4 ).setName( 'texture' );
  9380. /**
  9381. * TSL function for creating a texture node or sample a texture node already existing.
  9382. *
  9383. * @tsl
  9384. * @function
  9385. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  9386. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  9387. * @param {?Node<int>} [levelNode=null] - The level node.
  9388. * @param {?Node<float>} [biasNode=null] - The bias node.
  9389. * @returns {TextureNode}
  9390. */
  9391. const texture = ( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) => {
  9392. let textureNode;
  9393. if ( value && value.isTextureNode === true ) {
  9394. textureNode = nodeObject( value.clone() );
  9395. textureNode.referenceNode = value.getBase(); // Ensure the reference is set to the original node
  9396. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  9397. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  9398. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  9399. } else {
  9400. textureNode = textureBase( value, uvNode, levelNode, biasNode );
  9401. }
  9402. return textureNode;
  9403. };
  9404. /**
  9405. * TSL function for creating a uniform texture node.
  9406. *
  9407. * @tsl
  9408. * @function
  9409. * @param {?Texture} value - The texture.
  9410. * @returns {TextureNode}
  9411. */
  9412. const uniformTexture = ( value = EmptyTexture$1 ) => texture( value );
  9413. /**
  9414. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  9415. *
  9416. * @tsl
  9417. * @function
  9418. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  9419. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  9420. * @param {?Node<int>} [levelNode=null] - The level node.
  9421. * @param {?Node<float>} [biasNode=null] - The bias node.
  9422. * @returns {TextureNode}
  9423. */
  9424. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  9425. const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  9426. /**
  9427. * Converts a texture or texture node to a sampler.
  9428. *
  9429. * @tsl
  9430. * @function
  9431. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  9432. * @returns {Node}
  9433. */
  9434. const sampler = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'sampler' );
  9435. /**
  9436. * Converts a texture or texture node to a sampler comparison.
  9437. *
  9438. * @tsl
  9439. * @function
  9440. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  9441. * @returns {Node}
  9442. */
  9443. const samplerComparison = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'samplerComparison' );
  9444. /**
  9445. * A special type of uniform node which represents array-like data
  9446. * as uniform buffers. The access usually happens via `element()`
  9447. * which returns an instance of {@link ArrayElementNode}. For example:
  9448. *
  9449. * ```js
  9450. * const bufferNode = buffer( array, 'mat4', count );
  9451. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  9452. * ```
  9453. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  9454. * since it handles more input types and automatically cares about buffer paddings.
  9455. *
  9456. * @augments UniformNode
  9457. */
  9458. class BufferNode extends UniformNode {
  9459. static get type() {
  9460. return 'BufferNode';
  9461. }
  9462. /**
  9463. * Constructs a new buffer node.
  9464. *
  9465. * @param {Array<number>} value - Array-like buffer data.
  9466. * @param {string} bufferType - The data type of the buffer.
  9467. * @param {number} [bufferCount=0] - The count of buffer elements.
  9468. */
  9469. constructor( value, bufferType, bufferCount = 0 ) {
  9470. super( value, bufferType );
  9471. /**
  9472. * This flag can be used for type testing.
  9473. *
  9474. * @type {boolean}
  9475. * @readonly
  9476. * @default true
  9477. */
  9478. this.isBufferNode = true;
  9479. /**
  9480. * The data type of the buffer.
  9481. *
  9482. * @type {string}
  9483. */
  9484. this.bufferType = bufferType;
  9485. /**
  9486. * The uniform node that holds the value of the reference node.
  9487. *
  9488. * @type {number}
  9489. * @default 0
  9490. */
  9491. this.bufferCount = bufferCount;
  9492. /**
  9493. * An array of update ranges.
  9494. *
  9495. * @type {Array<{start: number, count: number}>}
  9496. */
  9497. this.updateRanges = [];
  9498. }
  9499. /**
  9500. * Adds a range of data in the data array to be updated on the GPU.
  9501. *
  9502. * @param {number} start - Position at which to start update.
  9503. * @param {number} count - The number of components to update.
  9504. */
  9505. addUpdateRange( start, count ) {
  9506. this.updateRanges.push( { start, count } );
  9507. }
  9508. /**
  9509. * Clears the update ranges.
  9510. */
  9511. clearUpdateRanges() {
  9512. this.updateRanges.length = 0;
  9513. }
  9514. /**
  9515. * The data type of the buffer elements.
  9516. *
  9517. * @param {NodeBuilder} builder - The current node builder.
  9518. * @return {string} The element type.
  9519. */
  9520. getElementType( builder ) {
  9521. return this.getNodeType( builder );
  9522. }
  9523. /**
  9524. * Overwrites the default implementation to return a fixed value `'buffer'`.
  9525. *
  9526. * @param {NodeBuilder} builder - The current node builder.
  9527. * @return {string} The input type.
  9528. */
  9529. getInputType( /*builder*/ ) {
  9530. return 'buffer';
  9531. }
  9532. }
  9533. /**
  9534. * TSL function for creating a buffer node.
  9535. *
  9536. * @tsl
  9537. * @function
  9538. * @param {Array<number>} value - Array-like buffer data.
  9539. * @param {string} type - The data type of a buffer element.
  9540. * @param {number} count - The count of buffer elements.
  9541. * @returns {BufferNode}
  9542. */
  9543. const buffer = ( value, type, count ) => new BufferNode( value, type, count );
  9544. /**
  9545. * Represents the element access on uniform array nodes.
  9546. *
  9547. * @augments ArrayElementNode
  9548. */
  9549. class UniformArrayElementNode extends ArrayElementNode {
  9550. static get type() {
  9551. return 'UniformArrayElementNode';
  9552. }
  9553. /**
  9554. * Constructs a new buffer node.
  9555. *
  9556. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  9557. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  9558. */
  9559. constructor( uniformArrayNode, indexNode ) {
  9560. super( uniformArrayNode, indexNode );
  9561. /**
  9562. * This flag can be used for type testing.
  9563. *
  9564. * @type {boolean}
  9565. * @readonly
  9566. * @default true
  9567. */
  9568. this.isArrayBufferElementNode = true;
  9569. }
  9570. generate( builder ) {
  9571. const snippet = super.generate( builder );
  9572. const type = this.getNodeType( builder );
  9573. const paddedType = this.node.getPaddedType();
  9574. return builder.format( snippet, paddedType, type );
  9575. }
  9576. }
  9577. /**
  9578. * Similar to {@link BufferNode} this module represents array-like data as
  9579. * uniform buffers. Unlike {@link BufferNode}, it can handle more common
  9580. * data types in the array (e.g `three.js` primitives) and automatically
  9581. * manage buffer padding. It should be the first choice when working with
  9582. * uniforms buffers.
  9583. * ```js
  9584. * const tintColors = uniformArray( [
  9585. * new Color( 1, 0, 0 ),
  9586. * new Color( 0, 1, 0 ),
  9587. * new Color( 0, 0, 1 )
  9588. * ], 'color' );
  9589. *
  9590. * const redColor = tintColors.element( 0 );
  9591. *
  9592. * @augments BufferNode
  9593. */
  9594. class UniformArrayNode extends BufferNode {
  9595. static get type() {
  9596. return 'UniformArrayNode';
  9597. }
  9598. /**
  9599. * Constructs a new uniform array node.
  9600. *
  9601. * @param {Array<any>} value - Array holding the buffer data.
  9602. * @param {?string} [elementType=null] - The data type of a buffer element.
  9603. */
  9604. constructor( value, elementType = null ) {
  9605. super( null );
  9606. /**
  9607. * Array holding the buffer data. Unlike {@link BufferNode}, the array can
  9608. * hold number primitives as well as three.js objects like vectors, matrices
  9609. * or colors.
  9610. *
  9611. * @type {Array<any>}
  9612. */
  9613. this.array = value;
  9614. /**
  9615. * The data type of an array element.
  9616. *
  9617. * @type {string}
  9618. */
  9619. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  9620. /**
  9621. * The padded type. Uniform buffers must conform to a certain buffer layout
  9622. * so a separate type is computed to ensure correct buffer size.
  9623. *
  9624. * @type {string}
  9625. */
  9626. this.paddedType = this.getPaddedType();
  9627. /**
  9628. * Overwritten since uniform array nodes are updated per render.
  9629. *
  9630. * @type {string}
  9631. * @default 'render'
  9632. */
  9633. this.updateType = NodeUpdateType.RENDER;
  9634. /**
  9635. * This flag can be used for type testing.
  9636. *
  9637. * @type {boolean}
  9638. * @readonly
  9639. * @default true
  9640. */
  9641. this.isArrayBufferNode = true;
  9642. }
  9643. /**
  9644. * This method is overwritten since the node type is inferred from the
  9645. * {@link UniformArrayNode#paddedType}.
  9646. *
  9647. * @param {NodeBuilder} builder - The current node builder.
  9648. * @return {string} The node type.
  9649. */
  9650. generateNodeType( /*builder*/ ) {
  9651. return this.paddedType;
  9652. }
  9653. /**
  9654. * The data type of the array elements.
  9655. *
  9656. * @param {NodeBuilder} builder - The current node builder.
  9657. * @return {string} The element type.
  9658. */
  9659. getElementType() {
  9660. return this.elementType;
  9661. }
  9662. /**
  9663. * Returns the padded type based on the element type.
  9664. *
  9665. * @return {string} The padded type.
  9666. */
  9667. getPaddedType() {
  9668. const elementType = this.elementType;
  9669. let paddedType = 'vec4';
  9670. if ( elementType === 'mat2' ) {
  9671. paddedType = 'mat2';
  9672. } else if ( /mat/.test( elementType ) === true ) {
  9673. paddedType = 'mat4';
  9674. } else if ( elementType.charAt( 0 ) === 'i' ) {
  9675. paddedType = 'ivec4';
  9676. } else if ( elementType.charAt( 0 ) === 'u' ) {
  9677. paddedType = 'uvec4';
  9678. }
  9679. return paddedType;
  9680. }
  9681. update( /*frame*/ ) {
  9682. this.updateBuffer();
  9683. }
  9684. /**
  9685. * Composes a user-defined update with the buffer transfer.
  9686. *
  9687. * @param {Function} callback - The update function.
  9688. * @param {string} updateType - The update type.
  9689. * @return {UniformArrayNode} A reference to this node.
  9690. */
  9691. onUpdate( callback, updateType ) {
  9692. callback = callback.bind( this );
  9693. return super.onUpdate( ( frame, self ) => {
  9694. callback( frame, self );
  9695. this.updateBuffer();
  9696. }, updateType );
  9697. }
  9698. /**
  9699. * The method makes sure to correctly transfer the data from the (complex) objects
  9700. * in the array to the internal, correctly padded value buffer.
  9701. */
  9702. updateBuffer() {
  9703. const { array, value } = this;
  9704. const elementType = this.elementType;
  9705. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  9706. for ( let i = 0; i < array.length; i ++ ) {
  9707. const index = i * 4;
  9708. value[ index ] = array[ i ];
  9709. }
  9710. } else if ( elementType === 'color' ) {
  9711. for ( let i = 0; i < array.length; i ++ ) {
  9712. const index = i * 4;
  9713. const vector = array[ i ];
  9714. value[ index ] = vector.r;
  9715. value[ index + 1 ] = vector.g;
  9716. value[ index + 2 ] = vector.b || 0;
  9717. //value[ index + 3 ] = vector.a || 0;
  9718. }
  9719. } else if ( elementType === 'mat2' ) {
  9720. for ( let i = 0; i < array.length; i ++ ) {
  9721. const index = i * 4;
  9722. const matrix = array[ i ];
  9723. value[ index ] = matrix.elements[ 0 ];
  9724. value[ index + 1 ] = matrix.elements[ 1 ];
  9725. value[ index + 2 ] = matrix.elements[ 2 ];
  9726. value[ index + 3 ] = matrix.elements[ 3 ];
  9727. }
  9728. } else if ( elementType === 'mat3' ) {
  9729. for ( let i = 0; i < array.length; i ++ ) {
  9730. const index = i * 16;
  9731. const matrix = array[ i ];
  9732. value[ index ] = matrix.elements[ 0 ];
  9733. value[ index + 1 ] = matrix.elements[ 1 ];
  9734. value[ index + 2 ] = matrix.elements[ 2 ];
  9735. value[ index + 4 ] = matrix.elements[ 3 ];
  9736. value[ index + 5 ] = matrix.elements[ 4 ];
  9737. value[ index + 6 ] = matrix.elements[ 5 ];
  9738. value[ index + 8 ] = matrix.elements[ 6 ];
  9739. value[ index + 9 ] = matrix.elements[ 7 ];
  9740. value[ index + 10 ] = matrix.elements[ 8 ];
  9741. value[ index + 15 ] = 1;
  9742. }
  9743. } else if ( elementType === 'mat4' ) {
  9744. for ( let i = 0; i < array.length; i ++ ) {
  9745. const index = i * 16;
  9746. const matrix = array[ i ];
  9747. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  9748. value[ index + i ] = matrix.elements[ i ];
  9749. }
  9750. }
  9751. } else {
  9752. for ( let i = 0; i < array.length; i ++ ) {
  9753. const index = i * 4;
  9754. const vector = array[ i ];
  9755. value[ index ] = vector.x;
  9756. value[ index + 1 ] = vector.y;
  9757. value[ index + 2 ] = vector.z || 0;
  9758. value[ index + 3 ] = vector.w || 0;
  9759. }
  9760. }
  9761. }
  9762. /**
  9763. * Implement the value buffer creation based on the array data.
  9764. *
  9765. * @param {NodeBuilder} builder - A reference to the current node builder.
  9766. * @return {null}
  9767. */
  9768. setup( builder ) {
  9769. const length = this.array.length;
  9770. const elementType = this.elementType;
  9771. let arrayType = Float32Array;
  9772. const paddedType = this.paddedType;
  9773. const paddedElementLength = builder.getTypeLength( paddedType );
  9774. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  9775. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  9776. this.value = new arrayType( length * paddedElementLength );
  9777. this.bufferCount = length;
  9778. this.bufferType = paddedType;
  9779. this.updateBuffer(); // initialize the buffer values
  9780. return super.setup( builder );
  9781. }
  9782. /**
  9783. * Overwrites the default `element()` method to provide element access
  9784. * based on {@link UniformArrayNode}.
  9785. *
  9786. * @param {IndexNode} indexNode - The index node.
  9787. * @return {UniformArrayElementNode}
  9788. */
  9789. element( indexNode ) {
  9790. return new UniformArrayElementNode( this, nodeObject( indexNode ) );
  9791. }
  9792. }
  9793. /**
  9794. * TSL function for creating an uniform array node.
  9795. *
  9796. * @tsl
  9797. * @function
  9798. * @param {Array<any>} values - Array-like data.
  9799. * @param {?string} [nodeType] - The data type of the array elements.
  9800. * @returns {UniformArrayNode}
  9801. */
  9802. const uniformArray = ( values, nodeType ) => new UniformArrayNode( values, nodeType );
  9803. /**
  9804. * The node allows to set values for built-in shader variables. That is
  9805. * required for features like hardware-accelerated vertex clipping.
  9806. *
  9807. * @augments Node
  9808. */
  9809. class BuiltinNode extends Node {
  9810. /**
  9811. * Constructs a new builtin node.
  9812. *
  9813. * @param {string} name - The name of the built-in shader variable.
  9814. */
  9815. constructor( name ) {
  9816. super( 'float' );
  9817. /**
  9818. * The name of the built-in shader variable.
  9819. *
  9820. * @type {string}
  9821. */
  9822. this.name = name;
  9823. /**
  9824. * This flag can be used for type testing.
  9825. *
  9826. * @type {boolean}
  9827. * @readonly
  9828. * @default true
  9829. */
  9830. this.isBuiltinNode = true;
  9831. }
  9832. /**
  9833. * Generates the code snippet of the builtin node.
  9834. *
  9835. * @param {NodeBuilder} builder - The current node builder.
  9836. * @return {string} The generated code snippet.
  9837. */
  9838. generate( /* builder */ ) {
  9839. return this.name;
  9840. }
  9841. }
  9842. /**
  9843. * TSL function for creating a builtin node.
  9844. *
  9845. * @tsl
  9846. * @function
  9847. * @param {string} name - The name of the built-in shader variable.
  9848. * @returns {BuiltinNode}
  9849. */
  9850. const builtin = nodeProxy( BuiltinNode ).setParameterLength( 1 );
  9851. let _screenSizeVec, _viewportVec;
  9852. /**
  9853. * This node provides a collection of screen related metrics.
  9854. * Depending on {@link ScreenNode#scope}, the nodes can represent
  9855. * resolution or viewport data as well as fragment or uv coordinates.
  9856. *
  9857. * @augments Node
  9858. */
  9859. class ScreenNode extends Node {
  9860. static get type() {
  9861. return 'ScreenNode';
  9862. }
  9863. /**
  9864. * Constructs a new screen node.
  9865. *
  9866. * @param {('coordinate'|'viewport'|'size'|'uv'|'dpr')} scope - The node's scope.
  9867. */
  9868. constructor( scope ) {
  9869. super();
  9870. /**
  9871. * The node represents different metric depending on which scope is selected.
  9872. *
  9873. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  9874. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  9875. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  9876. * - `ScreenNode.UV`: Normalized coordinates.
  9877. * - `ScreenNode.DPR`: Device pixel ratio.
  9878. *
  9879. * @type {('coordinate'|'viewport'|'size'|'uv'|'dpr')}
  9880. */
  9881. this.scope = scope;
  9882. /**
  9883. * This output node.
  9884. *
  9885. * @private
  9886. * @type {?Node}
  9887. * @default null
  9888. */
  9889. this._output = null;
  9890. /**
  9891. * This flag can be used for type testing.
  9892. *
  9893. * @type {boolean}
  9894. * @readonly
  9895. * @default true
  9896. */
  9897. this.isViewportNode = true;
  9898. }
  9899. /**
  9900. * This method is overwritten since the node type depends on the selected scope.
  9901. *
  9902. * @return {('float'|'vec2'|'vec4')} The node type.
  9903. */
  9904. generateNodeType() {
  9905. if ( this.scope === ScreenNode.DPR ) return 'float';
  9906. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  9907. else return 'vec2';
  9908. }
  9909. /**
  9910. * This method is overwritten since the node's update type depends on the selected scope.
  9911. *
  9912. * @return {NodeUpdateType} The update type.
  9913. */
  9914. getUpdateType() {
  9915. let updateType = NodeUpdateType.NONE;
  9916. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT || this.scope === ScreenNode.DPR ) {
  9917. updateType = NodeUpdateType.RENDER;
  9918. }
  9919. this.updateType = updateType;
  9920. return updateType;
  9921. }
  9922. /**
  9923. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  9924. * from the current renderer.
  9925. *
  9926. * @param {NodeFrame} frame - A reference to the current node frame.
  9927. */
  9928. update( { renderer } ) {
  9929. const renderTarget = renderer.getRenderTarget();
  9930. if ( this.scope === ScreenNode.VIEWPORT ) {
  9931. if ( renderTarget !== null ) {
  9932. _viewportVec.copy( renderTarget.viewport );
  9933. } else {
  9934. renderer.getViewport( _viewportVec );
  9935. _viewportVec.multiplyScalar( renderer.getPixelRatio() );
  9936. }
  9937. } else if ( this.scope === ScreenNode.DPR ) {
  9938. this._output.value = renderer.getPixelRatio();
  9939. } else {
  9940. if ( renderTarget !== null ) {
  9941. _screenSizeVec.width = renderTarget.width;
  9942. _screenSizeVec.height = renderTarget.height;
  9943. } else {
  9944. renderer.getDrawingBufferSize( _screenSizeVec );
  9945. }
  9946. }
  9947. }
  9948. setup( /*builder*/ ) {
  9949. const scope = this.scope;
  9950. let output = null;
  9951. if ( scope === ScreenNode.SIZE ) {
  9952. output = uniform( _screenSizeVec || ( _screenSizeVec = new Vector2() ) );
  9953. } else if ( scope === ScreenNode.VIEWPORT ) {
  9954. output = uniform( _viewportVec || ( _viewportVec = new Vector4() ) );
  9955. } else if ( scope === ScreenNode.DPR ) {
  9956. output = uniform( 1 );
  9957. } else {
  9958. output = vec2( screenCoordinate.div( screenSize ) );
  9959. }
  9960. this._output = output;
  9961. return output;
  9962. }
  9963. generate( builder ) {
  9964. if ( this.scope === ScreenNode.COORDINATE ) {
  9965. let coord = builder.getFragCoord();
  9966. if ( builder.isFlipY() ) {
  9967. // follow webgpu standards
  9968. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  9969. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  9970. }
  9971. return coord;
  9972. }
  9973. return super.generate( builder );
  9974. }
  9975. }
  9976. ScreenNode.COORDINATE = 'coordinate';
  9977. ScreenNode.VIEWPORT = 'viewport';
  9978. ScreenNode.SIZE = 'size';
  9979. ScreenNode.UV = 'uv';
  9980. ScreenNode.DPR = 'dpr';
  9981. // Screen
  9982. /**
  9983. * TSL object that represents the current DPR.
  9984. *
  9985. * @tsl
  9986. * @type {ScreenNode<float>}
  9987. */
  9988. const screenDPR = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.DPR );
  9989. /**
  9990. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  9991. *
  9992. * @tsl
  9993. * @type {ScreenNode<vec2>}
  9994. */
  9995. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  9996. /**
  9997. * TSL object that represents the screen resolution in physical pixel units.
  9998. *
  9999. * @tsl
  10000. * @type {ScreenNode<vec2>}
  10001. */
  10002. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  10003. /**
  10004. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  10005. *
  10006. * @tsl
  10007. * @type {ScreenNode<vec2>}
  10008. */
  10009. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  10010. // Viewport
  10011. /**
  10012. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  10013. *
  10014. * @tsl
  10015. * @type {ScreenNode<vec4>}
  10016. */
  10017. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  10018. /**
  10019. * TSL object that represents the viewport resolution in physical pixel units.
  10020. *
  10021. * @tsl
  10022. * @type {ScreenNode<vec2>}
  10023. */
  10024. const viewportSize = viewport.zw;
  10025. /**
  10026. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  10027. *
  10028. * @tsl
  10029. * @type {ScreenNode<vec2>}
  10030. */
  10031. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  10032. /**
  10033. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  10034. *
  10035. * @tsl
  10036. * @type {ScreenNode<vec2>}
  10037. */
  10038. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  10039. // Cache node uniforms
  10040. let _cameraProjectionMatrixBase = null;
  10041. let _cameraProjectionMatrixArray = null;
  10042. let _cameraProjectionMatrixInverseBase = null;
  10043. let _cameraProjectionMatrixInverseArray = null;
  10044. let _cameraViewMatrixBase = null;
  10045. let _cameraViewMatrixArray = null;
  10046. let _cameraWorldMatrixBase = null;
  10047. let _cameraWorldMatrixArray = null;
  10048. let _cameraNormalMatrixBase = null;
  10049. let _cameraNormalMatrixArray = null;
  10050. let _cameraPositionBase = null;
  10051. let _cameraPositionArray = null;
  10052. let _cameraViewportBase = null;
  10053. let _cameraViewportArray = null;
  10054. /**
  10055. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  10056. *
  10057. * @tsl
  10058. * @type {UniformNode<uint>}
  10059. */
  10060. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).setName( 'u_cameraIndex' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  10061. /**
  10062. * TSL object that represents the `near` value of the camera used for the current render.
  10063. *
  10064. * @tsl
  10065. * @type {UniformNode<float>}
  10066. */
  10067. const cameraNear = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  10068. /**
  10069. * TSL object that represents the `far` value of the camera used for the current render.
  10070. *
  10071. * @tsl
  10072. * @type {UniformNode<float>}
  10073. */
  10074. const cameraFar = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  10075. /**
  10076. * TSL object that represents the projection matrix of the camera used for the current render.
  10077. *
  10078. * @tsl
  10079. * @type {UniformNode<mat4>}
  10080. */
  10081. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  10082. let cameraProjectionMatrix;
  10083. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  10084. const matrices = [];
  10085. for ( const subCamera of camera.cameras ) {
  10086. matrices.push( subCamera.projectionMatrix );
  10087. }
  10088. if ( _cameraProjectionMatrixArray === null ) {
  10089. _cameraProjectionMatrixArray = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatrices' );
  10090. } else {
  10091. _cameraProjectionMatrixArray.array = matrices;
  10092. }
  10093. cameraProjectionMatrix = _cameraProjectionMatrixArray.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex );
  10094. } else {
  10095. if ( _cameraProjectionMatrixBase === null ) {
  10096. _cameraProjectionMatrixBase = uniform( camera.projectionMatrix ).setName( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  10097. }
  10098. cameraProjectionMatrix = _cameraProjectionMatrixBase;
  10099. }
  10100. return cameraProjectionMatrix;
  10101. } ).once() )();
  10102. /**
  10103. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  10104. *
  10105. * @tsl
  10106. * @type {UniformNode<mat4>}
  10107. */
  10108. const cameraProjectionMatrixInverse = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  10109. let cameraProjectionMatrixInverse;
  10110. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  10111. const matrices = [];
  10112. for ( const subCamera of camera.cameras ) {
  10113. matrices.push( subCamera.projectionMatrixInverse );
  10114. }
  10115. if ( _cameraProjectionMatrixInverseArray === null ) {
  10116. _cameraProjectionMatrixInverseArray = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatricesInverse' );
  10117. } else {
  10118. _cameraProjectionMatrixInverseArray.array = matrices;
  10119. }
  10120. cameraProjectionMatrixInverse = _cameraProjectionMatrixInverseArray.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex );
  10121. } else {
  10122. if ( _cameraProjectionMatrixInverseBase === null ) {
  10123. _cameraProjectionMatrixInverseBase = uniform( camera.projectionMatrixInverse ).setName( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  10124. }
  10125. cameraProjectionMatrixInverse = _cameraProjectionMatrixInverseBase;
  10126. }
  10127. return cameraProjectionMatrixInverse;
  10128. } ).once() )();
  10129. /**
  10130. * TSL object that represents the view matrix of the camera used for the current render.
  10131. *
  10132. * @tsl
  10133. * @type {UniformNode<mat4>}
  10134. */
  10135. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  10136. let cameraViewMatrix;
  10137. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  10138. const matrices = [];
  10139. for ( const subCamera of camera.cameras ) {
  10140. matrices.push( subCamera.matrixWorldInverse );
  10141. }
  10142. if ( _cameraViewMatrixArray === null ) {
  10143. _cameraViewMatrixArray = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraViewMatrices' );
  10144. } else {
  10145. _cameraViewMatrixArray.array = matrices;
  10146. }
  10147. cameraViewMatrix = _cameraViewMatrixArray.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex );
  10148. } else {
  10149. if ( _cameraViewMatrixBase === null ) {
  10150. _cameraViewMatrixBase = uniform( camera.matrixWorldInverse ).setName( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  10151. }
  10152. cameraViewMatrix = _cameraViewMatrixBase;
  10153. }
  10154. return cameraViewMatrix;
  10155. } ).once() )();
  10156. /**
  10157. * TSL object that represents the world matrix of the camera used for the current render.
  10158. *
  10159. * @tsl
  10160. * @type {UniformNode<mat4>}
  10161. */
  10162. const cameraWorldMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  10163. let cameraWorldMatrix;
  10164. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  10165. const matrices = [];
  10166. for ( const subCamera of camera.cameras ) {
  10167. matrices.push( subCamera.matrixWorld );
  10168. }
  10169. if ( _cameraWorldMatrixArray === null ) {
  10170. _cameraWorldMatrixArray = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraWorldMatrices' );
  10171. } else {
  10172. _cameraWorldMatrixArray.array = matrices;
  10173. }
  10174. cameraWorldMatrix = _cameraWorldMatrixArray.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex );
  10175. } else {
  10176. if ( _cameraWorldMatrixBase === null ) {
  10177. _cameraWorldMatrixBase = uniform( camera.matrixWorld ).setName( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  10178. }
  10179. cameraWorldMatrix = _cameraWorldMatrixBase;
  10180. }
  10181. return cameraWorldMatrix;
  10182. } ).once() )();
  10183. /**
  10184. * TSL object that represents the normal matrix of the camera used for the current render.
  10185. *
  10186. * @tsl
  10187. * @type {UniformNode<mat3>}
  10188. */
  10189. const cameraNormalMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  10190. let cameraNormalMatrix;
  10191. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  10192. const matrices = [];
  10193. for ( const subCamera of camera.cameras ) {
  10194. matrices.push( subCamera.normalMatrix );
  10195. }
  10196. if ( _cameraNormalMatrixArray === null ) {
  10197. _cameraNormalMatrixArray = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraNormalMatrices' );
  10198. } else {
  10199. _cameraNormalMatrixArray.array = matrices;
  10200. }
  10201. cameraNormalMatrix = _cameraNormalMatrixArray.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex );
  10202. } else {
  10203. if ( _cameraNormalMatrixBase === null ) {
  10204. _cameraNormalMatrixBase = uniform( camera.normalMatrix ).setName( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  10205. }
  10206. cameraNormalMatrix = _cameraNormalMatrixBase;
  10207. }
  10208. return cameraNormalMatrix;
  10209. } ).once() )();
  10210. /**
  10211. * TSL object that represents the position in world space of the camera used for the current render.
  10212. *
  10213. * @tsl
  10214. * @type {UniformNode<vec3>}
  10215. */
  10216. const cameraPosition = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  10217. let cameraPosition;
  10218. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  10219. const positions = [];
  10220. for ( let i = 0, l = camera.cameras.length; i < l; i ++ ) {
  10221. positions.push( new Vector3() );
  10222. }
  10223. if ( _cameraPositionArray === null ) {
  10224. _cameraPositionArray = uniformArray( positions ).setGroup( renderGroup ).setName( 'cameraPositions' ).onRenderUpdate( ( { camera }, self ) => {
  10225. const subCameras = camera.cameras;
  10226. const array = self.array;
  10227. for ( let i = 0, l = subCameras.length; i < l; i ++ ) {
  10228. array[ i ].setFromMatrixPosition( subCameras[ i ].matrixWorld );
  10229. }
  10230. } );
  10231. } else {
  10232. _cameraPositionArray.array = positions;
  10233. }
  10234. cameraPosition = _cameraPositionArray.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex );
  10235. } else {
  10236. if ( _cameraPositionBase === null ) {
  10237. _cameraPositionBase = uniform( new Vector3() ).setName( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  10238. }
  10239. cameraPosition = _cameraPositionBase;
  10240. }
  10241. return cameraPosition;
  10242. } ).once() )();
  10243. /**
  10244. * TSL object that represents the viewport of the camera used for the current render.
  10245. *
  10246. * @tsl
  10247. * @type {UniformNode<vec4>}
  10248. */
  10249. const cameraViewport = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  10250. let cameraViewport;
  10251. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  10252. const viewports = [];
  10253. for ( const subCamera of camera.cameras ) {
  10254. viewports.push( subCamera.viewport );
  10255. }
  10256. if ( _cameraViewportArray === null ) {
  10257. _cameraViewportArray = uniformArray( viewports, 'vec4' ).setGroup( renderGroup ).setName( 'cameraViewports' );
  10258. } else {
  10259. _cameraViewportArray.array = viewports;
  10260. }
  10261. cameraViewport = _cameraViewportArray.element( cameraIndex );
  10262. } else {
  10263. if ( _cameraViewportBase === null ) {
  10264. // Fallback for single camera
  10265. _cameraViewportBase = vec4( 0, 0, screenSize.x, screenSize.y ).toConst( 'cameraViewport' );
  10266. }
  10267. cameraViewport = _cameraViewportBase;
  10268. }
  10269. return cameraViewport;
  10270. } ).once() )();
  10271. const _sphere = /*@__PURE__*/ new Sphere();
  10272. /**
  10273. * This node can be used to access transformation related metrics of 3D objects.
  10274. * Depending on the selected scope, a different metric is represented as a uniform
  10275. * in the shader. The following scopes are supported:
  10276. *
  10277. * - `POSITION`: The object's position in world space.
  10278. * - `VIEW_POSITION`: The object's position in view/camera space.
  10279. * - `DIRECTION`: The object's direction in world space.
  10280. * - `SCALE`: The object's scale in world space.
  10281. * - `WORLD_MATRIX`: The object's matrix in world space.
  10282. *
  10283. * @augments Node
  10284. */
  10285. class Object3DNode extends Node {
  10286. static get type() {
  10287. return 'Object3DNode';
  10288. }
  10289. /**
  10290. * Constructs a new object 3D node.
  10291. *
  10292. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  10293. * @param {?Object3D} [object3d=null] - The 3D object.
  10294. */
  10295. constructor( scope, object3d = null ) {
  10296. super();
  10297. /**
  10298. * The node reports a different type of transformation depending on the scope.
  10299. *
  10300. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  10301. */
  10302. this.scope = scope;
  10303. /**
  10304. * The 3D object.
  10305. *
  10306. * @type {?Object3D}
  10307. * @default null
  10308. */
  10309. this.object3d = object3d;
  10310. /**
  10311. * Overwritten since this type of node is updated per object.
  10312. *
  10313. * @type {string}
  10314. * @default 'object'
  10315. */
  10316. this.updateType = NodeUpdateType.OBJECT;
  10317. /**
  10318. * Holds the value of the node as a uniform.
  10319. *
  10320. * @type {UniformNode}
  10321. */
  10322. this.uniformNode = new UniformNode( null );
  10323. }
  10324. /**
  10325. * Overwritten since the node type is inferred from the scope.
  10326. *
  10327. * @return {('mat4'|'vec3'|'float')} The node type.
  10328. */
  10329. generateNodeType() {
  10330. const scope = this.scope;
  10331. if ( scope === Object3DNode.WORLD_MATRIX ) {
  10332. return 'mat4';
  10333. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  10334. return 'vec3';
  10335. } else if ( scope === Object3DNode.RADIUS ) {
  10336. return 'float';
  10337. }
  10338. }
  10339. /**
  10340. * Updates the uniform value depending on the scope.
  10341. *
  10342. * @param {NodeFrame} frame - The current node frame.
  10343. */
  10344. update( frame ) {
  10345. const object = this.object3d;
  10346. const uniformNode = this.uniformNode;
  10347. const scope = this.scope;
  10348. if ( scope === Object3DNode.WORLD_MATRIX ) {
  10349. uniformNode.value = object.matrixWorld;
  10350. } else if ( scope === Object3DNode.POSITION ) {
  10351. uniformNode.value = uniformNode.value || new Vector3();
  10352. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  10353. } else if ( scope === Object3DNode.SCALE ) {
  10354. uniformNode.value = uniformNode.value || new Vector3();
  10355. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  10356. } else if ( scope === Object3DNode.DIRECTION ) {
  10357. uniformNode.value = uniformNode.value || new Vector3();
  10358. object.getWorldDirection( uniformNode.value );
  10359. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  10360. const camera = frame.camera;
  10361. uniformNode.value = uniformNode.value || new Vector3();
  10362. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  10363. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  10364. } else if ( scope === Object3DNode.RADIUS ) {
  10365. const geometry = frame.object.geometry;
  10366. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  10367. _sphere.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  10368. uniformNode.value = _sphere.radius;
  10369. }
  10370. }
  10371. /**
  10372. * Generates the code snippet of the uniform node. The node type of the uniform
  10373. * node also depends on the selected scope.
  10374. *
  10375. * @param {NodeBuilder} builder - The current node builder.
  10376. * @return {string} The generated code snippet.
  10377. */
  10378. generate( builder ) {
  10379. const scope = this.scope;
  10380. if ( scope === Object3DNode.WORLD_MATRIX ) {
  10381. this.uniformNode.nodeType = 'mat4';
  10382. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  10383. this.uniformNode.nodeType = 'vec3';
  10384. } else if ( scope === Object3DNode.RADIUS ) {
  10385. this.uniformNode.nodeType = 'float';
  10386. }
  10387. return this.uniformNode.build( builder );
  10388. }
  10389. serialize( data ) {
  10390. super.serialize( data );
  10391. data.scope = this.scope;
  10392. }
  10393. deserialize( data ) {
  10394. super.deserialize( data );
  10395. this.scope = data.scope;
  10396. }
  10397. }
  10398. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  10399. Object3DNode.POSITION = 'position';
  10400. Object3DNode.SCALE = 'scale';
  10401. Object3DNode.VIEW_POSITION = 'viewPosition';
  10402. Object3DNode.DIRECTION = 'direction';
  10403. Object3DNode.RADIUS = 'radius';
  10404. /**
  10405. * TSL function for creating an object 3D node that represents the object's direction in world space.
  10406. *
  10407. * @tsl
  10408. * @function
  10409. * @param {?Object3D} [object3d] - The 3D object.
  10410. * @returns {Object3DNode<vec3>}
  10411. */
  10412. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION ).setParameterLength( 1 );
  10413. /**
  10414. * TSL function for creating an object 3D node that represents the object's world matrix.
  10415. *
  10416. * @tsl
  10417. * @function
  10418. * @param {?Object3D} [object3d] - The 3D object.
  10419. * @returns {Object3DNode<mat4>}
  10420. */
  10421. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ).setParameterLength( 1 );
  10422. /**
  10423. * TSL function for creating an object 3D node that represents the object's position in world space.
  10424. *
  10425. * @tsl
  10426. * @function
  10427. * @param {?Object3D} [object3d] - The 3D object.
  10428. * @returns {Object3DNode<vec3>}
  10429. */
  10430. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION ).setParameterLength( 1 );
  10431. /**
  10432. * TSL function for creating an object 3D node that represents the object's scale in world space.
  10433. *
  10434. * @tsl
  10435. * @function
  10436. * @param {?Object3D} [object3d] - The 3D object.
  10437. * @returns {Object3DNode<vec3>}
  10438. */
  10439. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE ).setParameterLength( 1 );
  10440. /**
  10441. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  10442. *
  10443. * @tsl
  10444. * @function
  10445. * @param {?Object3D} [object3d] - The 3D object.
  10446. * @returns {Object3DNode<vec3>}
  10447. */
  10448. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ).setParameterLength( 1 );
  10449. /**
  10450. * TSL function for creating an object 3D node that represents the object's radius.
  10451. *
  10452. * @tsl
  10453. * @function
  10454. * @param {?Object3D} [object3d] - The 3D object.
  10455. * @returns {Object3DNode<float>}
  10456. */
  10457. const objectRadius = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.RADIUS ).setParameterLength( 1 );
  10458. /**
  10459. * This type of node is a specialized version of `Object3DNode`
  10460. * with larger set of model related metrics. Unlike `Object3DNode`,
  10461. * `ModelNode` extracts the reference to the 3D object from the
  10462. * current node frame state.
  10463. *
  10464. * @augments Object3DNode
  10465. */
  10466. class ModelNode extends Object3DNode {
  10467. static get type() {
  10468. return 'ModelNode';
  10469. }
  10470. /**
  10471. * Constructs a new object model node.
  10472. *
  10473. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  10474. */
  10475. constructor( scope ) {
  10476. super( scope );
  10477. }
  10478. /**
  10479. * Extracts the model reference from the frame state and then
  10480. * updates the uniform value depending on the scope.
  10481. *
  10482. * @param {NodeFrame} frame - The current node frame.
  10483. */
  10484. update( frame ) {
  10485. this.object3d = frame.object;
  10486. super.update( frame );
  10487. }
  10488. }
  10489. /**
  10490. * TSL object that represents the object's direction in world space.
  10491. *
  10492. * @tsl
  10493. * @type {ModelNode<vec3>}
  10494. */
  10495. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  10496. /**
  10497. * TSL object that represents the object's world matrix.
  10498. *
  10499. * @tsl
  10500. * @type {ModelNode<mat4>}
  10501. */
  10502. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  10503. /**
  10504. * TSL object that represents the object's position in world space.
  10505. *
  10506. * @tsl
  10507. * @type {ModelNode<vec3>}
  10508. */
  10509. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  10510. /**
  10511. * TSL object that represents the object's scale in world space.
  10512. *
  10513. * @tsl
  10514. * @type {ModelNode<vec3>}
  10515. */
  10516. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  10517. /**
  10518. * TSL object that represents the object's position in view/camera space.
  10519. *
  10520. * @tsl
  10521. * @type {ModelNode<vec3>}
  10522. */
  10523. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  10524. /**
  10525. * TSL object that represents the object's radius.
  10526. *
  10527. * @tsl
  10528. * @type {ModelNode<float>}
  10529. */
  10530. const modelRadius = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.RADIUS );
  10531. /**
  10532. * TSL object that represents the object's normal matrix.
  10533. *
  10534. * @tsl
  10535. * @type {UniformNode<mat3>}
  10536. */
  10537. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  10538. /**
  10539. * TSL object that represents the object's inverse world matrix.
  10540. *
  10541. * @tsl
  10542. * @type {UniformNode<mat4>}
  10543. */
  10544. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  10545. /**
  10546. * TSL object that represents the object's model view matrix.
  10547. *
  10548. * @tsl
  10549. * @type {Node<mat4>}
  10550. */
  10551. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  10552. return builder.context.modelViewMatrix || mediumpModelViewMatrix;
  10553. } ).once() )().toVar( 'modelViewMatrix' );
  10554. // GPU Precision
  10555. /**
  10556. * TSL object that represents the object's model view in `mediump` precision.
  10557. *
  10558. * @tsl
  10559. * @type {Node<mat4>}
  10560. */
  10561. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  10562. // CPU Precision
  10563. /**
  10564. * TSL object that represents the object's model view in `highp` precision
  10565. * which is achieved by computing the matrix in JS and not in the shader.
  10566. *
  10567. * @tsl
  10568. * @type {Node<mat4>}
  10569. */
  10570. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  10571. builder.context.isHighPrecisionModelViewMatrix = true;
  10572. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  10573. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  10574. } );
  10575. } ).once() )().toVar( 'highpModelViewMatrix' );
  10576. /**
  10577. * TSL object that represents the object's model normal view in `highp` precision
  10578. * which is achieved by computing the matrix in JS and not in the shader.
  10579. *
  10580. * @tsl
  10581. * @type {Node<mat3>}
  10582. */
  10583. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  10584. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  10585. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  10586. if ( isHighPrecisionModelViewMatrix !== true ) {
  10587. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  10588. }
  10589. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  10590. } );
  10591. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  10592. /**
  10593. * TSL object that represents the clip space position of the current rendered object.
  10594. *
  10595. * @tsl
  10596. * @type {VaryingNode<vec4>}
  10597. */
  10598. const clipSpace = /*@__PURE__*/ ( Fn( ( builder ) => {
  10599. if ( builder.shaderStage !== 'fragment' ) {
  10600. warnOnce( 'TSL: `clipSpace` is only available in fragment stage.' );
  10601. return vec4();
  10602. }
  10603. return builder.context.clipSpace.toVarying( 'v_clipSpace' );
  10604. } ).once() )();
  10605. /**
  10606. * TSL object that represents the position attribute of the current rendered object.
  10607. *
  10608. * @tsl
  10609. * @type {AttributeNode<vec3>}
  10610. */
  10611. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  10612. /**
  10613. * TSL object that represents the transformed vertex position in local space of the current rendered object.
  10614. *
  10615. * The term "transformed" indicates that an object or material's properties, such as skinning, batch,
  10616. * instancing, or displacement mapping, will change the vertex position of the node when present.
  10617. * To use the pre-transformed local space position of the object, use {@link positionGeometry}.
  10618. *
  10619. * @tsl
  10620. * @type {AttributeNode<vec3>}
  10621. */
  10622. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  10623. /**
  10624. * TSL object that represents the previous vertex position in local space of the current rendered object.
  10625. * Used in context of {@link VelocityNode} for rendering motion vectors.
  10626. *
  10627. * @tsl
  10628. * @type {AttributeNode<vec3>}
  10629. */
  10630. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  10631. /**
  10632. * TSL object that represents the vertex position in world space of the current rendered object.
  10633. *
  10634. * @tsl
  10635. * @type {VaryingNode<vec3>}
  10636. */
  10637. const positionWorld = /*@__PURE__*/ ( Fn( ( builder ) => {
  10638. return modelWorldMatrix.mul( positionLocal ).xyz.toVarying( builder.getSubBuildProperty( 'v_positionWorld' ) );
  10639. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  10640. /**
  10641. * TSL object that represents the position world direction of the current rendered object.
  10642. *
  10643. * @tsl
  10644. * @type {Node<vec3>}
  10645. */
  10646. const positionWorldDirection = /*@__PURE__*/ ( Fn( () => {
  10647. const vertexPWD = positionLocal.transformDirection( modelWorldMatrix ).toVarying( 'v_positionWorldDirection' );
  10648. return vertexPWD.normalize().toVar( 'positionWorldDirection' );
  10649. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  10650. /**
  10651. * TSL object that represents the vertex position in view space of the current rendered object.
  10652. *
  10653. * @tsl
  10654. * @type {VaryingNode<vec3>}
  10655. */
  10656. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  10657. if ( builder.shaderStage === 'fragment' && builder.material.vertexNode ) {
  10658. // reconstruct view position from clip space
  10659. const viewPos = cameraProjectionMatrixInverse.mul( clipSpace );
  10660. return viewPos.xyz.div( viewPos.w ).toVar( 'positionView' );
  10661. }
  10662. return builder.context.setupPositionView().toVarying( 'v_positionView' );
  10663. }, 'vec3' ).once( [ 'POSITION', 'VERTEX' ] ) )();
  10664. /**
  10665. * TSL object that represents the position view direction of the current rendered object.
  10666. *
  10667. * @tsl
  10668. * @type {VaryingNode<vec3>}
  10669. */
  10670. const positionViewDirection = /*@__PURE__*/ ( Fn( ( builder ) => {
  10671. let output;
  10672. if ( builder.camera.isOrthographicCamera ) {
  10673. output = vec3( 0, 0, 1 );
  10674. } else {
  10675. output = positionView.negate().toVarying( 'v_positionViewDirection' ).normalize();
  10676. }
  10677. return output.toVar( 'positionViewDirection' );
  10678. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  10679. /**
  10680. * This node can be used to evaluate whether a primitive is front or back facing.
  10681. *
  10682. * @augments Node
  10683. */
  10684. class FrontFacingNode extends Node {
  10685. static get type() {
  10686. return 'FrontFacingNode';
  10687. }
  10688. /**
  10689. * Constructs a new front facing node.
  10690. */
  10691. constructor() {
  10692. super( 'bool' );
  10693. /**
  10694. * This flag can be used for type testing.
  10695. *
  10696. * @type {boolean}
  10697. * @readonly
  10698. * @default true
  10699. */
  10700. this.isFrontFacingNode = true;
  10701. }
  10702. generate( builder ) {
  10703. if ( builder.shaderStage !== 'fragment' ) return 'true';
  10704. //
  10705. const { material } = builder;
  10706. if ( material.side === BackSide ) {
  10707. return 'false';
  10708. }
  10709. return builder.getFrontFacing();
  10710. }
  10711. }
  10712. /**
  10713. * TSL object that represents whether a primitive is front or back facing
  10714. *
  10715. * @tsl
  10716. * @type {FrontFacingNode<bool>}
  10717. */
  10718. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  10719. /**
  10720. * TSL object that represents the front facing status as a number instead of a bool.
  10721. * `1` means front facing, `-1` means back facing.
  10722. *
  10723. * @tsl
  10724. * @type {Node<float>}
  10725. */
  10726. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  10727. /**
  10728. * Negates a vector if the rendering occurs on the back side of a face,
  10729. * based on the material's side configuration.
  10730. *
  10731. * - If the material's side is `BackSide`, the vector is inverted (negated).
  10732. * - If the material's side is `DoubleSide`, the vector is multiplied by `faceDirection`
  10733. * (negated only for back-facing fragments).
  10734. * - If the material's side is `FrontSide` (default), the vector remains unchanged.
  10735. *
  10736. * @tsl
  10737. * @function
  10738. * @param {Node<vec3>} vector - The vector to process.
  10739. * @returns {Node<vec3>} The processed vector.
  10740. */
  10741. const negateOnBackSide = /*@__PURE__*/ Fn( ( [ vector ], { material } ) => {
  10742. const side = material.side;
  10743. if ( side === BackSide ) {
  10744. vector = vector.mul( -1 );
  10745. } else if ( side === DoubleSide ) {
  10746. vector = vector.mul( faceDirection );
  10747. }
  10748. return vector;
  10749. } );
  10750. /**
  10751. * Negates a vector if the rendering occurs on the back side of a face,
  10752. * based on the material's side configuration.
  10753. *
  10754. * - If the material's side is `BackSide`, the vector is inverted (negated).
  10755. * - If the material's side is `DoubleSide`, the vector is multiplied by `faceDirection`
  10756. * (negated only for back-facing fragments).
  10757. * - If the material's side is `FrontSide` (default), the vector remains unchanged.
  10758. *
  10759. * @tsl
  10760. * @function
  10761. * @deprecated since r185. Use {@link negateOnBackSide} instead.
  10762. * @param {Node<vec3>} vector - The vector to convert.
  10763. * @returns {Node<vec3>} The converted vector.
  10764. */
  10765. const directionToFaceDirection = ( vector ) => {
  10766. warnOnce( 'TSL: "directionToFaceDirection()" has been renamed to "negateOnBackSide()".' ); // @deprecated r185
  10767. return negateOnBackSide( vector );
  10768. };
  10769. /**
  10770. * TSL object that represents the normal attribute of the current rendered object in local space.
  10771. *
  10772. * @tsl
  10773. * @type {Node<vec3>}
  10774. */
  10775. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  10776. /**
  10777. * TSL object that represents the vertex normal of the current rendered object in local space.
  10778. *
  10779. * @tsl
  10780. * @type {Node<vec3>}
  10781. */
  10782. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  10783. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  10784. warn( 'TSL: Vertex attribute "normal" not found on geometry.' );
  10785. return vec3( 0, 1, 0 );
  10786. }
  10787. return normalGeometry;
  10788. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  10789. /**
  10790. * TSL object that represents the flat vertex normal of the current rendered object in view space.
  10791. *
  10792. * @tsl
  10793. * @type {Node<vec3>}
  10794. */
  10795. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  10796. /**
  10797. * TSL object that represents the vertex normal of the current rendered object in view space.
  10798. *
  10799. * @tsl
  10800. * @type {Node<vec3>}
  10801. */
  10802. const normalViewGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  10803. let node;
  10804. if ( builder.isFlatShading() ) {
  10805. node = normalFlat;
  10806. } else {
  10807. node = transformNormalToView( normalLocal ).toVarying( 'v_normalViewGeometry' ).normalize();
  10808. }
  10809. return node;
  10810. }, 'vec3' ).once() )().toVar( 'normalViewGeometry' );
  10811. /**
  10812. * TSL object that represents the vertex normal of the current rendered object in world space.
  10813. *
  10814. * @tsl
  10815. * @type {Node<vec3>}
  10816. */
  10817. const normalWorldGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  10818. let normal = normalViewGeometry.transformNormalByInverseViewMatrix( cameraViewMatrix );
  10819. if ( builder.isFlatShading() !== true ) {
  10820. normal = normal.toVarying( 'v_normalWorldGeometry' );
  10821. }
  10822. return normal.normalize().toVar( 'normalWorldGeometry' );
  10823. }, 'vec3' ).once() )();
  10824. /**
  10825. * TSL object that represents the vertex normal of the current rendered object in view space.
  10826. *
  10827. * @tsl
  10828. * @type {Node<vec3>}
  10829. */
  10830. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  10831. let node;
  10832. if ( builder.subBuildFn === 'NORMAL' || builder.subBuildFn === 'VERTEX' ) {
  10833. node = normalViewGeometry;
  10834. if ( builder.isFlatShading() !== true ) {
  10835. node = negateOnBackSide( node );
  10836. }
  10837. } else {
  10838. // Use custom context to avoid side effects from nodes overwriting getUV, getTextureLevel in the context (e.g. EnvironmentNode)
  10839. node = builder.context.setupNormal().context( { getUV: null, getTextureLevel: null } );
  10840. }
  10841. return node;
  10842. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'normalView' );
  10843. /**
  10844. * TSL object that represents the vertex normal of the current rendered object in world space.
  10845. *
  10846. * @tsl
  10847. * @type {Node<vec3>}
  10848. */
  10849. const normalWorld = /*@__PURE__*/ normalView.transformNormalByInverseViewMatrix( cameraViewMatrix ).toVar( 'normalWorld' );
  10850. /**
  10851. * TSL object that represents the clearcoat vertex normal of the current rendered object in view space.
  10852. *
  10853. * @tsl
  10854. * @type {Node<vec3>}
  10855. */
  10856. const clearcoatNormalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, context } ) => {
  10857. let node;
  10858. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  10859. node = normalView;
  10860. } else {
  10861. // Use custom context to avoid side effects from nodes overwriting getUV, getTextureLevel in the context (e.g. EnvironmentNode)
  10862. node = context.setupClearcoatNormal().context( { getUV: null, getTextureLevel: null } );
  10863. }
  10864. return node;
  10865. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'clearcoatNormalView' );
  10866. /**
  10867. * Transforms the normal by the normal matrix of the given matrix and then normalizes the result.
  10868. *
  10869. * @tsl
  10870. * @function
  10871. * @param {Node<vec3>} normal - The normal.
  10872. * @param {Node<mat3|mat4>} [matrix=modelWorldMatrix] - The matrix.
  10873. * @return {Node<vec3>} The transformed normal.
  10874. */
  10875. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  10876. const normalMatrix = mat3( matrix ).inverse().transpose();
  10877. return normalMatrix.mul( normal ).normalize();
  10878. } );
  10879. addMethodChaining( 'transformNormal', transformNormal );
  10880. /**
  10881. * Transforms the given normal from local to view space.
  10882. *
  10883. * @tsl
  10884. * @function
  10885. * @param {Node<vec3>} normal - The normal.
  10886. * @param {NodeBuilder} builder - The current node builder.
  10887. * @return {Node<vec3>} The transformed normal.
  10888. */
  10889. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  10890. const modelNormalViewMatrix = builder.context.modelNormalViewMatrix;
  10891. if ( modelNormalViewMatrix ) {
  10892. return normal.transformNormalByViewMatrix( modelNormalViewMatrix );
  10893. }
  10894. //
  10895. const transformedNormal = modelNormalMatrix.mul( normal );
  10896. return transformedNormal.transformNormalByViewMatrix( cameraViewMatrix );
  10897. } );
  10898. // Deprecated
  10899. /**
  10900. * TSL object that represents the transformed vertex normal of the current rendered object in view space.
  10901. *
  10902. * @tsl
  10903. * @type {Node<vec3>}
  10904. * @deprecated since r178. Use `normalView` instead.
  10905. */
  10906. const transformedNormalView = ( Fn( () => { // @deprecated, r177
  10907. warn( 'TSL: "transformedNormalView" is deprecated. Use "normalView" instead.' );
  10908. return normalView;
  10909. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10910. /**
  10911. * TSL object that represents the transformed vertex normal of the current rendered object in world space.
  10912. *
  10913. * @tsl
  10914. * @type {Node<vec3>}
  10915. * @deprecated since r178. Use `normalWorld` instead.
  10916. */
  10917. const transformedNormalWorld = ( Fn( () => { // @deprecated, r177
  10918. warn( 'TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.' );
  10919. return normalWorld;
  10920. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10921. /**
  10922. * TSL object that represents the transformed clearcoat vertex normal of the current rendered object in view space.
  10923. *
  10924. * @tsl
  10925. * @type {Node<vec3>}
  10926. * @deprecated since r178. Use `clearcoatNormalView` instead.
  10927. */
  10928. const transformedClearcoatNormalView = ( Fn( () => { // @deprecated, r177
  10929. warn( 'TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.' );
  10930. return clearcoatNormalView;
  10931. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10932. const _m1$1 = /*@__PURE__*/ new Matrix4();
  10933. /**
  10934. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  10935. *
  10936. * @tsl
  10937. * @type {UniformNode<float>}
  10938. */
  10939. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onObjectUpdate( ( { material } ) => material.refractionRatio );
  10940. /**
  10941. * TSL object that represents the intensity of environment maps of PBR materials.
  10942. * When `material.envMap` is set, the value is `material.envMapIntensity` otherwise `scene.environmentIntensity`.
  10943. *
  10944. * @tsl
  10945. * @type {Node<float>}
  10946. */
  10947. const materialEnvIntensity = /*@__PURE__*/ uniform( 1 ).onReference( ( { material } ) => material ).onObjectUpdate( function ( { material, scene } ) {
  10948. return material.envMap ? material.envMapIntensity : scene.environmentIntensity;
  10949. } );
  10950. /**
  10951. * TSL object that represents the rotation of environment maps.
  10952. * When `material.envMap` is set, the value is `material.envMapRotation`.
  10953. * `scene.environmentRotation` controls the rotation of `scene.environment` or `scene.environmentNode` instead.
  10954. *
  10955. * @tsl
  10956. * @type {Node<mat4>}
  10957. */
  10958. const materialEnvRotation = /*@__PURE__*/ uniform( new Matrix4() ).onReference( function ( frame ) {
  10959. return frame.material;
  10960. } ).onObjectUpdate( function ( { material, scene } ) {
  10961. const hasSceneEnvironment = ( scene.environment !== null ) || ( scene.environmentNode && scene.environmentNode.isNode );
  10962. const rotation = ( hasSceneEnvironment && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  10963. if ( rotation ) {
  10964. // note: since the matrix is orthonormal, we can use the more-efficient transpose() in lieu of invert()
  10965. _m1$1.makeRotationFromEuler( rotation ).transpose();
  10966. } else {
  10967. _m1$1.identity();
  10968. }
  10969. return _m1$1;
  10970. } );
  10971. /**
  10972. * The reflect vector in view space.
  10973. *
  10974. * @tsl
  10975. * @type {Node<vec3>}
  10976. */
  10977. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( normalView );
  10978. /**
  10979. * The refract vector in view space.
  10980. *
  10981. * @tsl
  10982. * @type {Node<vec3>}
  10983. */
  10984. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( normalView, materialRefractionRatio );
  10985. /**
  10986. * Used for sampling cube maps when using cube reflection mapping.
  10987. *
  10988. * @tsl
  10989. * @type {Node<vec3>}
  10990. */
  10991. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraWorldMatrix ).toVar( 'reflectVector' );
  10992. /**
  10993. * Used for sampling cube maps when using cube refraction mapping.
  10994. *
  10995. * @tsl
  10996. * @type {Node<vec3>}
  10997. */
  10998. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraWorldMatrix ).toVar( 'refractVector' );
  10999. const EmptyTexture = /*@__PURE__*/ new CubeTexture();
  11000. /**
  11001. * This type of uniform node represents a cube texture.
  11002. *
  11003. * @augments TextureNode
  11004. */
  11005. class CubeTextureNode extends TextureNode {
  11006. static get type() {
  11007. return 'CubeTextureNode';
  11008. }
  11009. /**
  11010. * Constructs a new cube texture node.
  11011. *
  11012. * @param {CubeTexture} value - The cube texture.
  11013. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  11014. * @param {?Node<int>} [levelNode=null] - The level node.
  11015. * @param {?Node<float>} [biasNode=null] - The bias node.
  11016. */
  11017. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  11018. super( value, uvNode, levelNode, biasNode );
  11019. /**
  11020. * This flag can be used for type testing.
  11021. *
  11022. * @type {boolean}
  11023. * @readonly
  11024. * @default true
  11025. */
  11026. this.isCubeTextureNode = true;
  11027. }
  11028. /**
  11029. * Overwrites the default implementation to return the appropriate cube texture type.
  11030. *
  11031. * @param {NodeBuilder} builder - The current node builder.
  11032. * @return {string} The input type.
  11033. */
  11034. getInputType( /*builder*/ ) {
  11035. if ( this.value.isDepthTexture === true ) {
  11036. return 'cubeDepthTexture';
  11037. }
  11038. return 'cubeTexture';
  11039. }
  11040. /**
  11041. * Returns a default uvs based on the mapping type of the cube texture.
  11042. *
  11043. * @return {Node<vec3>} The default uv attribute.
  11044. */
  11045. getDefaultUV() {
  11046. const texture = this.value;
  11047. if ( texture.mapping === CubeReflectionMapping ) {
  11048. return reflectVector;
  11049. } else if ( texture.mapping === CubeRefractionMapping ) {
  11050. return refractVector;
  11051. } else {
  11052. error( 'CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  11053. return vec3( 0, 0, 0 );
  11054. }
  11055. }
  11056. /**
  11057. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  11058. * for cube textures. The uv transformation matrix is not applied to cube textures.
  11059. *
  11060. * @param {boolean} value - The update toggle.
  11061. */
  11062. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  11063. /**
  11064. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  11065. * to modify the uv node for correct sampling.
  11066. *
  11067. * @param {NodeBuilder} builder - The current node builder.
  11068. * @param {Node} uvNode - The uv node to setup.
  11069. * @return {Node} The updated uv node.
  11070. */
  11071. setupUV( builder, uvNode ) {
  11072. const texture = this.value;
  11073. // Depth textures (shadow maps) - no environment rotation, Y flip for WebGPU
  11074. if ( texture.isDepthTexture === true ) {
  11075. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  11076. return vec3( uvNode.x, uvNode.y.negate(), uvNode.z );
  11077. }
  11078. return uvNode;
  11079. }
  11080. // rotate first
  11081. uvNode = materialEnvRotation.mul( uvNode );
  11082. // flip
  11083. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  11084. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  11085. }
  11086. return uvNode;
  11087. }
  11088. /**
  11089. * Generates the uv code snippet.
  11090. *
  11091. * @param {NodeBuilder} builder - The current node builder.
  11092. * @param {Node} cubeUV - The uv node to generate code for.
  11093. * @return {string} The generated code snippet.
  11094. */
  11095. generateUV( builder, cubeUV ) {
  11096. return cubeUV.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  11097. }
  11098. }
  11099. /**
  11100. * TSL function for creating a cube texture node.
  11101. *
  11102. * @tsl
  11103. * @function
  11104. * @param {CubeTexture} value - The cube texture.
  11105. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  11106. * @param {?Node<int>} [levelNode=null] - The level node.
  11107. * @param {?Node<float>} [biasNode=null] - The bias node.
  11108. * @returns {CubeTextureNode}
  11109. */
  11110. const cubeTextureBase = /*@__PURE__*/ nodeProxy( CubeTextureNode ).setParameterLength( 1, 4 ).setName( 'cubeTexture' );
  11111. /**
  11112. * TSL function for creating a cube texture uniform node.
  11113. *
  11114. * @tsl
  11115. * @function
  11116. * @param {?(CubeTexture|CubeTextureNode)} [value=EmptyTexture] - The cube texture.
  11117. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  11118. * @param {?Node<int>} [levelNode=null] - The level node.
  11119. * @param {?Node<float>} [biasNode=null] - The bias node.
  11120. * @returns {CubeTextureNode}
  11121. */
  11122. const cubeTexture = ( value = EmptyTexture, uvNode = null, levelNode = null, biasNode = null ) => {
  11123. let textureNode;
  11124. if ( value && value.isCubeTextureNode === true ) {
  11125. textureNode = nodeObject( value.clone() );
  11126. textureNode.referenceNode = value; // Ensure the reference is set to the original node
  11127. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  11128. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  11129. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  11130. } else {
  11131. textureNode = cubeTextureBase( value, uvNode, levelNode, biasNode );
  11132. }
  11133. return textureNode;
  11134. };
  11135. /**
  11136. * TSL function for creating a uniform cube texture node.
  11137. *
  11138. * @tsl
  11139. * @function
  11140. * @param {?CubeTexture} [value=EmptyTexture] - The cube texture.
  11141. * @returns {CubeTextureNode}
  11142. */
  11143. const uniformCubeTexture = ( value = EmptyTexture ) => cubeTextureBase( value );
  11144. // TODO: Avoid duplicated code and use only ReferenceBaseNode or ReferenceNode
  11145. /**
  11146. * This class is only relevant if the referenced property is array-like.
  11147. * In this case, `ReferenceElementNode` allows to refer to a specific
  11148. * element inside the data structure via an index.
  11149. *
  11150. * @augments ArrayElementNode
  11151. */
  11152. class ReferenceElementNode extends ArrayElementNode {
  11153. static get type() {
  11154. return 'ReferenceElementNode';
  11155. }
  11156. /**
  11157. * Constructs a new reference element node.
  11158. *
  11159. * @param {?ReferenceNode} referenceNode - The reference node.
  11160. * @param {Node} indexNode - The index node that defines the element access.
  11161. */
  11162. constructor( referenceNode, indexNode ) {
  11163. super( referenceNode, indexNode );
  11164. /**
  11165. * Similar to {@link ReferenceNode#reference}, an additional
  11166. * property references to the current node.
  11167. *
  11168. * @type {?ReferenceNode}
  11169. * @default null
  11170. */
  11171. this.referenceNode = referenceNode;
  11172. /**
  11173. * This flag can be used for type testing.
  11174. *
  11175. * @type {boolean}
  11176. * @readonly
  11177. * @default true
  11178. */
  11179. this.isReferenceElementNode = true;
  11180. }
  11181. /**
  11182. * This method is overwritten since the node type is inferred from
  11183. * the uniform type of the reference node.
  11184. *
  11185. * @return {string} The node type.
  11186. */
  11187. generateNodeType() {
  11188. return this.referenceNode.uniformType;
  11189. }
  11190. generate( builder ) {
  11191. const snippet = super.generate( builder );
  11192. const arrayType = this.referenceNode.getNodeType( builder );
  11193. const elementType = this.getNodeType( builder );
  11194. return builder.format( snippet, arrayType, elementType );
  11195. }
  11196. }
  11197. /**
  11198. * This type of node establishes a reference to a property of another object.
  11199. * In this way, the value of the node is automatically linked to the value of
  11200. * referenced object. Reference nodes internally represent the linked value
  11201. * as a uniform.
  11202. *
  11203. * @augments Node
  11204. */
  11205. class ReferenceNode extends Node {
  11206. static get type() {
  11207. return 'ReferenceNode';
  11208. }
  11209. /**
  11210. * Constructs a new reference node.
  11211. *
  11212. * @param {string} property - The name of the property the node refers to.
  11213. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  11214. * @param {?Object} [object=null] - The object the property belongs to.
  11215. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  11216. */
  11217. constructor( property, uniformType, object = null, count = null ) {
  11218. super();
  11219. /**
  11220. * The name of the property the node refers to.
  11221. *
  11222. * @type {string}
  11223. */
  11224. this.property = property;
  11225. /**
  11226. * The uniform type that should be used to represent the property value.
  11227. *
  11228. * @type {string}
  11229. */
  11230. this.uniformType = uniformType;
  11231. /**
  11232. * The object the property belongs to.
  11233. *
  11234. * @type {?Object}
  11235. * @default null
  11236. */
  11237. this.object = object;
  11238. /**
  11239. * When the linked property is an array, this parameter defines its length.
  11240. *
  11241. * @type {?number}
  11242. * @default null
  11243. */
  11244. this.count = count;
  11245. /**
  11246. * The property name might have dots so nested properties can be referred.
  11247. * The hierarchy of the names is stored inside this array.
  11248. *
  11249. * @type {Array<string>}
  11250. */
  11251. this.properties = property.split( '.' );
  11252. /**
  11253. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  11254. * since the final reference might be updated from calling code.
  11255. *
  11256. * @type {?Object}
  11257. * @default null
  11258. */
  11259. this.reference = object;
  11260. /**
  11261. * The uniform node that holds the value of the reference node.
  11262. *
  11263. * @type {UniformNode}
  11264. * @default null
  11265. */
  11266. this.node = null;
  11267. /**
  11268. * The uniform group of the internal uniform.
  11269. *
  11270. * @type {UniformGroupNode}
  11271. * @default null
  11272. */
  11273. this.group = null;
  11274. /**
  11275. * An optional label of the internal uniform node.
  11276. *
  11277. * @type {?string}
  11278. * @default null
  11279. */
  11280. this.name = null;
  11281. /**
  11282. * Overwritten since reference nodes are updated per object.
  11283. *
  11284. * @type {string}
  11285. * @default 'object'
  11286. */
  11287. this.updateType = NodeUpdateType.OBJECT;
  11288. }
  11289. /**
  11290. * When the referred property is array-like, this method can be used
  11291. * to access elements via an index node.
  11292. *
  11293. * @param {IndexNode} indexNode - indexNode.
  11294. * @return {ReferenceElementNode} A reference to an element.
  11295. */
  11296. element( indexNode ) {
  11297. return new ReferenceElementNode( this, nodeObject( indexNode ) );
  11298. }
  11299. /**
  11300. * Sets the uniform group for this reference node.
  11301. *
  11302. * @param {UniformGroupNode} group - The uniform group to set.
  11303. * @return {ReferenceNode} A reference to this node.
  11304. */
  11305. setGroup( group ) {
  11306. this.group = group;
  11307. return this;
  11308. }
  11309. /**
  11310. * Sets the name for the internal uniform.
  11311. *
  11312. * @param {string} name - The label to set.
  11313. * @return {ReferenceNode} A reference to this node.
  11314. */
  11315. setName( name ) {
  11316. this.name = name;
  11317. return this;
  11318. }
  11319. /**
  11320. * Sets the label for the internal uniform.
  11321. *
  11322. * @deprecated
  11323. * @param {string} name - The label to set.
  11324. * @return {ReferenceNode} A reference to this node.
  11325. */
  11326. label( name ) {
  11327. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  11328. return this.setName( name );
  11329. }
  11330. /**
  11331. * Sets the node type which automatically defines the internal
  11332. * uniform type.
  11333. *
  11334. * @param {string} uniformType - The type to set.
  11335. */
  11336. setNodeType( uniformType ) {
  11337. let node = null;
  11338. if ( this.count !== null ) {
  11339. node = buffer( null, uniformType, this.count );
  11340. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  11341. node = uniformArray( null, uniformType );
  11342. node.updateType = NodeUpdateType.OBJECT;
  11343. } else if ( uniformType === 'texture' ) {
  11344. node = texture( null );
  11345. } else if ( uniformType === 'cubeTexture' ) {
  11346. node = cubeTexture( null );
  11347. } else {
  11348. node = uniform( null, uniformType );
  11349. }
  11350. if ( this.group !== null ) {
  11351. node.setGroup( this.group );
  11352. }
  11353. if ( this.name !== null ) node.setName( this.name );
  11354. this.node = node;
  11355. }
  11356. /**
  11357. * This method is overwritten since the node type is inferred from
  11358. * the type of the reference node.
  11359. *
  11360. * @param {NodeBuilder} builder - The current node builder.
  11361. * @return {string} The node type.
  11362. */
  11363. generateNodeType( builder ) {
  11364. if ( this.node === null ) {
  11365. this.updateReference( builder );
  11366. this.updateValue();
  11367. }
  11368. return this.node.getNodeType( builder );
  11369. }
  11370. /**
  11371. * Returns the property value from the given referred object.
  11372. *
  11373. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  11374. * @return {any} The value.
  11375. */
  11376. getValueFromReference( object = this.reference ) {
  11377. const { properties } = this;
  11378. let value = object[ properties[ 0 ] ];
  11379. for ( let i = 1; i < properties.length; i ++ ) {
  11380. value = value[ properties[ i ] ];
  11381. }
  11382. return value;
  11383. }
  11384. /**
  11385. * Allows to update the reference based on the given state. The state is only
  11386. * evaluated {@link ReferenceNode#object} is not set.
  11387. *
  11388. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  11389. * @return {Object} The updated reference.
  11390. */
  11391. updateReference( state ) {
  11392. this.reference = this.object !== null ? this.object : state.object;
  11393. return this.reference;
  11394. }
  11395. /**
  11396. * The output of the reference node is the internal uniform node.
  11397. *
  11398. * @param {NodeBuilder} builder - The current node builder.
  11399. * @return {UniformNode} The output node.
  11400. */
  11401. setup( /* builder */ ) {
  11402. this.updateValue();
  11403. return this.node;
  11404. }
  11405. /**
  11406. * Overwritten to update the internal uniform value.
  11407. *
  11408. * @param {NodeFrame} frame - A reference to the current node frame.
  11409. */
  11410. update( /*frame*/ ) {
  11411. this.updateValue();
  11412. }
  11413. /**
  11414. * Retrieves the value from the referred object property and uses it
  11415. * to updated the internal uniform.
  11416. */
  11417. updateValue() {
  11418. if ( this.node === null ) this.setNodeType( this.uniformType );
  11419. const value = this.getValueFromReference();
  11420. if ( Array.isArray( value ) ) {
  11421. this.node.array = value;
  11422. } else {
  11423. this.node.value = value;
  11424. }
  11425. }
  11426. }
  11427. /**
  11428. * TSL function for creating a reference node.
  11429. *
  11430. * @tsl
  11431. * @function
  11432. * @param {string} name - The name of the property the node refers to.
  11433. * @param {string} type - The uniform type that should be used to represent the property value.
  11434. * @param {?Object} [object] - The object the property belongs to.
  11435. * @returns {ReferenceNode}
  11436. */
  11437. const reference = ( name, type, object ) => new ReferenceNode( name, type, object );
  11438. /**
  11439. * TSL function for creating a reference node. Use this function if you want need a reference
  11440. * to an array-like property that should be represented as a uniform buffer.
  11441. *
  11442. * @tsl
  11443. * @function
  11444. * @param {string} name - The name of the property the node refers to.
  11445. * @param {string} type - The uniform type that should be used to represent the property value.
  11446. * @param {number} count - The number of value inside the array-like object.
  11447. * @param {Object} object - An array-like object the property belongs to.
  11448. * @returns {ReferenceNode}
  11449. */
  11450. const referenceBuffer = ( name, type, count, object ) => new ReferenceNode( name, type, object, count );
  11451. /**
  11452. * This node is a special type of reference node which is intended
  11453. * for linking material properties with node values.
  11454. * ```js
  11455. * const opacityNode = materialReference( 'opacity', 'float', material );
  11456. * ```
  11457. * When changing `material.opacity`, the node value of `opacityNode` will
  11458. * automatically be updated.
  11459. *
  11460. * @augments ReferenceNode
  11461. */
  11462. class MaterialReferenceNode extends ReferenceNode {
  11463. static get type() {
  11464. return 'MaterialReferenceNode';
  11465. }
  11466. /**
  11467. * Constructs a new material reference node.
  11468. *
  11469. * @param {string} property - The name of the property the node refers to.
  11470. * @param {string} inputType - The uniform type that should be used to represent the property value.
  11471. * @param {?Material} [material=null] - The material the property belongs to. When no material is set,
  11472. * the node refers to the material of the current rendered object.
  11473. */
  11474. constructor( property, inputType, material = null ) {
  11475. super( property, inputType, material );
  11476. /**
  11477. * The material the property belongs to. When no material is set,
  11478. * the node refers to the material of the current rendered object.
  11479. *
  11480. * @type {?Material}
  11481. * @default null
  11482. */
  11483. this.material = material;
  11484. /**
  11485. * This flag can be used for type testing.
  11486. *
  11487. * @type {boolean}
  11488. * @readonly
  11489. * @default true
  11490. */
  11491. this.isMaterialReferenceNode = true;
  11492. }
  11493. /**
  11494. * Updates the reference based on the given state. The state is only evaluated
  11495. * {@link MaterialReferenceNode#material} is not set.
  11496. *
  11497. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  11498. * @return {Object} The updated reference.
  11499. */
  11500. updateReference( state ) {
  11501. this.reference = this.material !== null ? this.material : state.material;
  11502. return this.reference;
  11503. }
  11504. }
  11505. /**
  11506. * TSL function for creating a material reference node.
  11507. *
  11508. * @tsl
  11509. * @function
  11510. * @param {string} name - The name of the property the node refers to.
  11511. * @param {string} type - The uniform type that should be used to represent the property value.
  11512. * @param {?Material} [material=null] - The material the property belongs to.
  11513. * When no material is set, the node refers to the material of the current rendered object.
  11514. * @returns {MaterialReferenceNode}
  11515. */
  11516. const materialReference = ( name, type, material = null ) => new MaterialReferenceNode( name, type, material );
  11517. // Normal Mapping Without Precomputed Tangents
  11518. // http://www.thetenthplanet.de/archives/1180
  11519. const uv = uv$1();
  11520. const q0 = positionView.dFdx();
  11521. const q1 = positionView.dFdy();
  11522. const st0 = uv.dFdx();
  11523. const st1 = uv.dFdy();
  11524. const N = normalView;
  11525. const q1perp = q1.cross( N );
  11526. const q0perp = N.cross( q0 );
  11527. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  11528. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  11529. const det = T.dot( T ).max( B.dot( B ) );
  11530. const scale$1 = det.equal( 0.0 ).select( 0.0, det.inverseSqrt() );
  11531. /**
  11532. * Tangent vector in view space, computed dynamically from geometry and UV derivatives.
  11533. * Useful for normal mapping without precomputed tangents.
  11534. *
  11535. * Reference: http://www.thetenthplanet.de/archives/1180
  11536. *
  11537. * @tsl
  11538. * @type {Node<vec3>}
  11539. */
  11540. const tangentViewFrame = /*@__PURE__*/ T.mul( scale$1 ).toVar( 'tangentViewFrame' );
  11541. /**
  11542. * Bitangent vector in view space, computed dynamically from geometry and UV derivatives.
  11543. * Complements the tangentViewFrame for constructing the tangent space basis.
  11544. *
  11545. * Reference: http://www.thetenthplanet.de/archives/1180
  11546. *
  11547. * @tsl
  11548. * @type {Node<vec3>}
  11549. */
  11550. const bitangentViewFrame = /*@__PURE__*/ B.mul( scale$1 ).toVar( 'bitangentViewFrame' );
  11551. /**
  11552. * TSL object that represents the tangent attribute of the current rendered object.
  11553. *
  11554. * @tsl
  11555. * @type {Node<vec4>}
  11556. */
  11557. const tangentGeometry = /*@__PURE__*/ attribute( 'tangent', 'vec4' );
  11558. /**
  11559. * TSL object that represents the vertex tangent in local space of the current rendered object.
  11560. *
  11561. * @tsl
  11562. * @type {Node<vec3>}
  11563. */
  11564. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  11565. /**
  11566. * TSL object that represents the vertex tangent in view space of the current rendered object.
  11567. *
  11568. * @tsl
  11569. * @type {Node<vec3>}
  11570. */
  11571. const tangentView = /*@__PURE__*/ ( Fn( ( builder ) => {
  11572. let node;
  11573. if ( builder.subBuildFn === 'VERTEX' || builder.geometry.hasAttribute( 'tangent' ) ) {
  11574. node = modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize();
  11575. } else {
  11576. node = tangentViewFrame;
  11577. }
  11578. if ( builder.isFlatShading() !== true ) {
  11579. node = negateOnBackSide( node );
  11580. }
  11581. return node;
  11582. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'tangentView' );
  11583. /**
  11584. * TSL object that represents the vertex tangent in world space of the current rendered object.
  11585. *
  11586. * @tsl
  11587. * @type {Node<vec3>}
  11588. */
  11589. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraWorldMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  11590. /**
  11591. * Returns the bitangent node and assigns it to a varying if the material is not flat shaded.
  11592. *
  11593. * @tsl
  11594. * @private
  11595. * @param {Node<vec3>} crossNormalTangent - The cross product of the normal and tangent vectors.
  11596. * @param {string} varyingName - The name of the varying to assign the bitangent to.
  11597. * @returns {Node<vec3>} The bitangent node.
  11598. */
  11599. const getBitangent = /*@__PURE__*/ Fn( ( [ crossNormalTangent, varyingName ], builder ) => {
  11600. let bitangent = crossNormalTangent.mul( tangentGeometry.w ).xyz;
  11601. if ( builder.subBuildFn === 'NORMAL' && builder.isFlatShading() !== true ) {
  11602. bitangent = bitangent.toVarying( varyingName );
  11603. }
  11604. return bitangent;
  11605. } ).once( [ 'NORMAL' ] );
  11606. /**
  11607. * TSL object that represents the bitangent attribute of the current rendered object.
  11608. *
  11609. * @tsl
  11610. * @type {Node<vec3>}
  11611. */
  11612. const bitangentGeometry = /*@__PURE__*/ getBitangent( normalGeometry.cross( tangentGeometry ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  11613. /**
  11614. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  11615. *
  11616. * @tsl
  11617. * @type {Node<vec3>}
  11618. */
  11619. const bitangentLocal = /*@__PURE__*/ getBitangent( normalLocal.cross( tangentLocal ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  11620. /**
  11621. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  11622. *
  11623. * @tsl
  11624. * @type {Node<vec3>}
  11625. */
  11626. const bitangentView = /*@__PURE__*/ ( Fn( ( builder ) => {
  11627. let node;
  11628. if ( builder.subBuildFn === 'VERTEX' || builder.geometry.hasAttribute( 'tangent' ) ) {
  11629. node = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize();
  11630. } else {
  11631. node = bitangentViewFrame;
  11632. }
  11633. if ( builder.isFlatShading() !== true ) {
  11634. node = negateOnBackSide( node );
  11635. }
  11636. return node;
  11637. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'bitangentView' );
  11638. /**
  11639. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  11640. *
  11641. * @tsl
  11642. * @type {Node<vec3>}
  11643. */
  11644. const bitangentWorld = /*@__PURE__*/ getBitangent( normalWorld.cross( tangentWorld ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  11645. /**
  11646. * TSL object that represents the TBN matrix in view space.
  11647. *
  11648. * @tsl
  11649. * @type {Node<mat3>}
  11650. */
  11651. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView ).toVar( 'TBNViewMatrix' );
  11652. /**
  11653. * TSL object that represents the parallax direction.
  11654. *
  11655. * @tsl
  11656. * @type {Node<mat3>}
  11657. */
  11658. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  11659. /**
  11660. * TSL function for computing parallax uv coordinates.
  11661. *
  11662. * @tsl
  11663. * @function
  11664. * @param {Node<vec2>} uv - A uv node.
  11665. * @param {Node<vec2>} scale - A scale node.
  11666. * @returns {Node<vec2>} Parallax uv coordinates.
  11667. */
  11668. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  11669. /**
  11670. * TSL function for computing bent normals.
  11671. *
  11672. * @tsl
  11673. * @function
  11674. * @returns {Node<vec3>} Bent normals.
  11675. */
  11676. const bentNormalView = /*@__PURE__*/ ( Fn( () => {
  11677. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  11678. let bentNormal = anisotropyB.cross( positionViewDirection );
  11679. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  11680. bentNormal = mix( bentNormal, normalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  11681. return bentNormal;
  11682. } ).once() )();
  11683. /**
  11684. * Packs a normal vector into a color value.
  11685. *
  11686. * @tsl
  11687. * @function
  11688. * @param {Node<vec3>} node - The direction to pack.
  11689. * @return {Node<vec3>} The color.
  11690. */
  11691. const packNormalToRGB = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  11692. /**
  11693. * Unpacks a color value into a normal vector.
  11694. *
  11695. * @tsl
  11696. * @function
  11697. * @param {Node<vec3>} node - The color to unpack.
  11698. * @return {Node<vec3>} The direction.
  11699. */
  11700. const unpackRGBToNormal = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  11701. /**
  11702. * Unpacks a tangent space normal, reconstructing the Z component by projecting the X,Y coordinates onto the hemisphere.
  11703. * The X,Y coordinates are expected to be in the [-1, 1] range.
  11704. *
  11705. * @tsl
  11706. * @function
  11707. * @param {Node<vec2>} xy - The X,Y coordinates of the normal.
  11708. * @return {Node<vec3>} The resulting normal.
  11709. */
  11710. const unpackNormal = ( xy ) => vec3( xy, sqrt( saturate( float( 1.0 ).sub( dot( xy, xy ) ) ) ) );
  11711. /**
  11712. * @tsl
  11713. * @function
  11714. * @deprecated since r185. Use {@link packNormalToRGB} instead.
  11715. * @param {Node<vec3>} node - The direction to pack.
  11716. * @returns {Node<vec3>}
  11717. */
  11718. const directionToColor = ( node ) => {
  11719. warnOnce( 'TSL: "directionToColor()" has been renamed to "packNormalToRGB()".' ); // @deprecated r185
  11720. return packNormalToRGB( node );
  11721. };
  11722. /**
  11723. * @tsl
  11724. * @function
  11725. * @deprecated since r185. Use {@link unpackRGBToNormal} instead.
  11726. * @param {Node<vec3>} node - The color to unpack.
  11727. * @returns {Node<vec3>}
  11728. */
  11729. const colorToDirection = ( node ) => {
  11730. warnOnce( 'TSL: "colorToDirection()" has been renamed to "unpackRGBToNormal()".' ); // @deprecated r185
  11731. return unpackRGBToNormal( node );
  11732. };
  11733. /**
  11734. * This class can be used for applying normals maps to materials.
  11735. *
  11736. * ```js
  11737. * material.normalNode = normalMap( texture( normalTex ) );
  11738. * ```
  11739. *
  11740. * @augments TempNode
  11741. */
  11742. class NormalMapNode extends TempNode {
  11743. static get type() {
  11744. return 'NormalMapNode';
  11745. }
  11746. /**
  11747. * Constructs a new normal map node.
  11748. *
  11749. * @param {Node<vec3>} node - Represents the normal map data.
  11750. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  11751. */
  11752. constructor( node, scaleNode = null ) {
  11753. super( 'vec3' );
  11754. /**
  11755. * Represents the normal map data.
  11756. *
  11757. * @type {Node<vec3>}
  11758. */
  11759. this.node = node;
  11760. /**
  11761. * Controls the intensity of the effect.
  11762. *
  11763. * @type {?Node<vec2>}
  11764. * @default null
  11765. */
  11766. this.scaleNode = scaleNode;
  11767. /**
  11768. * The normal map type.
  11769. *
  11770. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  11771. * @default TangentSpaceNormalMap
  11772. */
  11773. this.normalMapType = TangentSpaceNormalMap;
  11774. /**
  11775. * Controls how to unpack the sampled normal map values.
  11776. *
  11777. * @type {string}
  11778. * @default NoNormalPacking
  11779. */
  11780. this.unpackNormalMode = NoNormalPacking;
  11781. }
  11782. setup( builder ) {
  11783. const { normalMapType, scaleNode, unpackNormalMode } = this;
  11784. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  11785. if ( normalMapType === TangentSpaceNormalMap ) {
  11786. if ( unpackNormalMode === NormalRGPacking ) {
  11787. normalMap = unpackNormal( normalMap.xy );
  11788. } else if ( unpackNormalMode === NormalGAPacking ) {
  11789. normalMap = unpackNormal( normalMap.yw );
  11790. } else if ( unpackNormalMode !== NoNormalPacking ) {
  11791. error( `THREE.NodeMaterial: Unexpected unpack normal mode: ${ unpackNormalMode }` );
  11792. }
  11793. } else {
  11794. if ( unpackNormalMode !== NoNormalPacking ) {
  11795. error( `THREE.NodeMaterial: Normal map type '${ normalMapType }' is not compatible with unpack normal mode '${ unpackNormalMode }'` );
  11796. }
  11797. }
  11798. if ( scaleNode !== null ) {
  11799. let scale = scaleNode;
  11800. if ( builder.isFlatShading() === true ) {
  11801. scale = negateOnBackSide( scale );
  11802. }
  11803. normalMap = vec3( normalMap.xy.mul( scale ), normalMap.z );
  11804. }
  11805. let output = null;
  11806. if ( normalMapType === ObjectSpaceNormalMap ) {
  11807. output = transformNormalToView( normalMap );
  11808. } else if ( normalMapType === TangentSpaceNormalMap ) {
  11809. output = TBNViewMatrix.mul( normalMap ).normalize();
  11810. } else {
  11811. error( `NodeMaterial: Unsupported normal map type: ${ normalMapType }` );
  11812. output = normalView; // Fallback to default normal view
  11813. }
  11814. return output;
  11815. }
  11816. }
  11817. /**
  11818. * TSL function for creating a normal map node.
  11819. *
  11820. * @tsl
  11821. * @function
  11822. * @param {Node<vec3>} node - Represents the normal map data.
  11823. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  11824. * @returns {NormalMapNode}
  11825. */
  11826. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode ).setParameterLength( 1, 2 );
  11827. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  11828. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  11829. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  11830. // It's used to preserve the same TextureNode instance
  11831. const sampleTexture = ( callback ) => textureNode.isolate().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv$1() ), forceUVContext: true } );
  11832. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  11833. return vec2(
  11834. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  11835. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  11836. ).mul( bumpScale );
  11837. } );
  11838. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  11839. const perturbNormalArb = Fn( ( inputs ) => {
  11840. const { surf_pos, surf_norm, dHdxy } = inputs;
  11841. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  11842. const vSigmaX = surf_pos.dFdx().normalize();
  11843. const vSigmaY = surf_pos.dFdy().normalize();
  11844. const vN = surf_norm; // normalized
  11845. const R1 = vSigmaY.cross( vN );
  11846. const R2 = vN.cross( vSigmaX );
  11847. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  11848. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  11849. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  11850. } );
  11851. /**
  11852. * This class can be used for applying bump maps to materials.
  11853. *
  11854. * ```js
  11855. * material.normalNode = bumpMap( texture( bumpTex ) );
  11856. * ```
  11857. *
  11858. * @augments TempNode
  11859. */
  11860. class BumpMapNode extends TempNode {
  11861. static get type() {
  11862. return 'BumpMapNode';
  11863. }
  11864. /**
  11865. * Constructs a new bump map node.
  11866. *
  11867. * @param {Node<float>} textureNode - Represents the bump map data.
  11868. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  11869. */
  11870. constructor( textureNode, scaleNode = null ) {
  11871. super( 'vec3' );
  11872. /**
  11873. * Represents the bump map data.
  11874. *
  11875. * @type {Node<float>}
  11876. */
  11877. this.textureNode = textureNode;
  11878. /**
  11879. * Controls the intensity of the bump effect.
  11880. *
  11881. * @type {?Node<float>}
  11882. * @default null
  11883. */
  11884. this.scaleNode = scaleNode;
  11885. }
  11886. setup( builder ) {
  11887. // Screen-space derivatives are unreliable on thin lines, so the bump
  11888. // effect is disabled for wireframe rendering.
  11889. if ( builder.material.wireframe === true ) return normalView;
  11890. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  11891. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  11892. return perturbNormalArb( {
  11893. surf_pos: positionView,
  11894. surf_norm: normalView,
  11895. dHdxy
  11896. } );
  11897. }
  11898. }
  11899. /**
  11900. * TSL function for creating a bump map node.
  11901. *
  11902. * @tsl
  11903. * @function
  11904. * @param {Node<float>} textureNode - Represents the bump map data.
  11905. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  11906. * @returns {BumpMapNode}
  11907. */
  11908. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode ).setParameterLength( 1, 2 );
  11909. const _propertyCache = new Map();
  11910. /**
  11911. * This class should simplify the node access to material properties.
  11912. * It internal uses reference nodes to make sure changes to material
  11913. * properties are automatically reflected to predefined TSL objects
  11914. * like e.g. `materialColor`.
  11915. *
  11916. * @augments Node
  11917. */
  11918. class MaterialNode extends Node {
  11919. static get type() {
  11920. return 'MaterialNode';
  11921. }
  11922. /**
  11923. * Constructs a new material node.
  11924. *
  11925. * @param {string} scope - The scope defines what kind of material property is referred by the node.
  11926. */
  11927. constructor( scope ) {
  11928. super();
  11929. /**
  11930. * The scope defines what material property is referred by the node.
  11931. *
  11932. * @type {string}
  11933. */
  11934. this.scope = scope;
  11935. }
  11936. /**
  11937. * Returns a cached reference node for the given property and type.
  11938. *
  11939. * @param {string} property - The name of the material property.
  11940. * @param {string} type - The uniform type of the property.
  11941. * @return {MaterialReferenceNode} A material reference node representing the property access.
  11942. */
  11943. getCache( property, type ) {
  11944. let node = _propertyCache.get( property );
  11945. if ( node === undefined ) {
  11946. node = materialReference( property, type );
  11947. _propertyCache.set( property, node );
  11948. }
  11949. return node;
  11950. }
  11951. /**
  11952. * Returns a float-typed material reference node for the given property name.
  11953. *
  11954. * @param {string} property - The name of the material property.
  11955. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  11956. */
  11957. getFloat( property ) {
  11958. return this.getCache( property, 'float' );
  11959. }
  11960. /**
  11961. * Returns a color-typed material reference node for the given property name.
  11962. *
  11963. * @param {string} property - The name of the material property.
  11964. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  11965. */
  11966. getColor( property ) {
  11967. return this.getCache( property, 'color' );
  11968. }
  11969. /**
  11970. * Returns a texture-typed material reference node for the given property name.
  11971. *
  11972. * @param {string} property - The name of the material property.
  11973. * @return {MaterialReferenceNode} A material reference node representing the property access.
  11974. */
  11975. getTexture( property ) {
  11976. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  11977. }
  11978. /**
  11979. * The node setup is done depending on the selected scope. Multiple material properties
  11980. * might be grouped into a single node composition if they logically belong together.
  11981. *
  11982. * @param {NodeBuilder} builder - The current node builder.
  11983. * @return {Node} The node representing the selected scope.
  11984. */
  11985. setup( builder ) {
  11986. const material = builder.context.material;
  11987. const scope = this.scope;
  11988. let node = null;
  11989. if ( scope === MaterialNode.COLOR ) {
  11990. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  11991. if ( material.map && material.map.isTexture === true ) {
  11992. node = colorNode.mul( this.getTexture( 'map' ) );
  11993. } else {
  11994. node = colorNode;
  11995. }
  11996. } else if ( scope === MaterialNode.OPACITY ) {
  11997. const opacityNode = this.getFloat( scope );
  11998. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  11999. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  12000. } else {
  12001. node = opacityNode;
  12002. }
  12003. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  12004. if ( material.specularMap && material.specularMap.isTexture === true ) {
  12005. node = this.getTexture( 'specular' ).r;
  12006. } else {
  12007. node = float( 1 );
  12008. }
  12009. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  12010. const specularIntensityNode = this.getFloat( scope );
  12011. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  12012. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  12013. } else {
  12014. node = specularIntensityNode;
  12015. }
  12016. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  12017. const specularColorNode = this.getColor( scope );
  12018. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  12019. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  12020. } else {
  12021. node = specularColorNode;
  12022. }
  12023. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  12024. const roughnessNode = this.getFloat( scope );
  12025. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  12026. node = roughnessNode.mul( this.getTexture( scope ).g );
  12027. } else {
  12028. node = roughnessNode;
  12029. }
  12030. } else if ( scope === MaterialNode.METALNESS ) {
  12031. const metalnessNode = this.getFloat( scope );
  12032. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  12033. node = metalnessNode.mul( this.getTexture( scope ).b );
  12034. } else {
  12035. node = metalnessNode;
  12036. }
  12037. } else if ( scope === MaterialNode.EMISSIVE ) {
  12038. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  12039. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  12040. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  12041. node = emissiveNode.mul( this.getTexture( scope ) );
  12042. } else {
  12043. node = emissiveNode;
  12044. }
  12045. } else if ( scope === MaterialNode.NORMAL ) {
  12046. if ( material.normalMap ) {
  12047. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  12048. node.normalMapType = material.normalMapType;
  12049. if ( material.normalMap.format == RGFormat || material.normalMap.format == RED_GREEN_RGTC2_Format || material.normalMap.format == RG11_EAC_Format ) {
  12050. node.unpackNormalMode = NormalRGPacking;
  12051. }
  12052. } else if ( material.bumpMap ) {
  12053. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  12054. } else {
  12055. node = normalView;
  12056. }
  12057. } else if ( scope === MaterialNode.CLEARCOAT ) {
  12058. const clearcoatNode = this.getFloat( scope );
  12059. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  12060. node = clearcoatNode.mul( this.getTexture( scope ).r );
  12061. } else {
  12062. node = clearcoatNode;
  12063. }
  12064. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  12065. const clearcoatRoughnessNode = this.getFloat( scope );
  12066. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  12067. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  12068. } else {
  12069. node = clearcoatRoughnessNode;
  12070. }
  12071. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  12072. if ( material.clearcoatNormalMap ) {
  12073. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  12074. } else {
  12075. node = normalView;
  12076. }
  12077. } else if ( scope === MaterialNode.SHEEN ) {
  12078. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  12079. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  12080. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  12081. } else {
  12082. node = sheenNode;
  12083. }
  12084. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  12085. const sheenRoughnessNode = this.getFloat( scope );
  12086. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  12087. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  12088. } else {
  12089. node = sheenRoughnessNode;
  12090. }
  12091. node = node.clamp( 0.0001, 1.0 );
  12092. } else if ( scope === MaterialNode.ANISOTROPY ) {
  12093. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  12094. const anisotropyPolar = this.getTexture( scope );
  12095. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  12096. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  12097. } else {
  12098. node = materialAnisotropyVector;
  12099. }
  12100. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  12101. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  12102. if ( material.iridescenceThicknessMap ) {
  12103. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  12104. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  12105. } else {
  12106. node = iridescenceThicknessMaximum;
  12107. }
  12108. } else if ( scope === MaterialNode.TRANSMISSION ) {
  12109. const transmissionNode = this.getFloat( scope );
  12110. if ( material.transmissionMap ) {
  12111. node = transmissionNode.mul( this.getTexture( scope ).r );
  12112. } else {
  12113. node = transmissionNode;
  12114. }
  12115. } else if ( scope === MaterialNode.THICKNESS ) {
  12116. const thicknessNode = this.getFloat( scope );
  12117. if ( material.thicknessMap ) {
  12118. node = thicknessNode.mul( this.getTexture( scope ).g );
  12119. } else {
  12120. node = thicknessNode;
  12121. }
  12122. } else if ( scope === MaterialNode.IOR ) {
  12123. node = this.getFloat( scope );
  12124. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  12125. if ( material.lightMap ) {
  12126. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  12127. } else {
  12128. node = vec3( 0.0 );
  12129. }
  12130. } else if ( scope === MaterialNode.AO ) {
  12131. if ( material.aoMap ) {
  12132. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  12133. } else {
  12134. node = float( 1.0 );
  12135. }
  12136. } else if ( scope === MaterialNode.LINE_DASH_OFFSET ) {
  12137. node = ( material.dashOffset ) ? this.getFloat( scope ) : float( 0 );
  12138. } else {
  12139. const outputType = this.getNodeType( builder );
  12140. node = this.getCache( scope, outputType );
  12141. }
  12142. return node;
  12143. }
  12144. }
  12145. MaterialNode.ALPHA_TEST = 'alphaTest';
  12146. MaterialNode.COLOR = 'color';
  12147. MaterialNode.OPACITY = 'opacity';
  12148. MaterialNode.SHININESS = 'shininess';
  12149. MaterialNode.SPECULAR = 'specular';
  12150. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  12151. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  12152. MaterialNode.SPECULAR_COLOR = 'specularColor';
  12153. MaterialNode.REFLECTIVITY = 'reflectivity';
  12154. MaterialNode.ROUGHNESS = 'roughness';
  12155. MaterialNode.METALNESS = 'metalness';
  12156. MaterialNode.NORMAL = 'normal';
  12157. MaterialNode.CLEARCOAT = 'clearcoat';
  12158. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  12159. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  12160. MaterialNode.EMISSIVE = 'emissive';
  12161. MaterialNode.ROTATION = 'rotation';
  12162. MaterialNode.SHEEN = 'sheen';
  12163. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  12164. MaterialNode.ANISOTROPY = 'anisotropy';
  12165. MaterialNode.IRIDESCENCE = 'iridescence';
  12166. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  12167. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  12168. MaterialNode.IOR = 'ior';
  12169. MaterialNode.TRANSMISSION = 'transmission';
  12170. MaterialNode.THICKNESS = 'thickness';
  12171. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  12172. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  12173. MaterialNode.LINE_SCALE = 'scale';
  12174. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  12175. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  12176. MaterialNode.LINE_WIDTH = 'linewidth';
  12177. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  12178. MaterialNode.POINT_SIZE = 'size';
  12179. MaterialNode.DISPERSION = 'dispersion';
  12180. MaterialNode.RETROREFLECTIVE = 'retroreflective';
  12181. MaterialNode.LIGHT_MAP = 'light';
  12182. MaterialNode.AO = 'ao';
  12183. /**
  12184. * TSL object that represents alpha test of the current material.
  12185. *
  12186. * @tsl
  12187. * @type {Node<float>}
  12188. */
  12189. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  12190. /**
  12191. * TSL object that represents the diffuse color of the current material.
  12192. * The value is composed via `color` * `map`.
  12193. *
  12194. * @tsl
  12195. * @type {Node<vec3>}
  12196. */
  12197. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  12198. /**
  12199. * TSL object that represents the shininess of the current material.
  12200. *
  12201. * @tsl
  12202. * @type {Node<float>}
  12203. */
  12204. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  12205. /**
  12206. * TSL object that represents the emissive color of the current material.
  12207. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  12208. *
  12209. * @tsl
  12210. * @type {Node<vec3>}
  12211. */
  12212. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  12213. /**
  12214. * TSL object that represents the opacity of the current material.
  12215. * The value is composed via `opacity` * `alphaMap`.
  12216. *
  12217. * @tsl
  12218. * @type {Node<float>}
  12219. */
  12220. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  12221. /**
  12222. * TSL object that represents the specular of the current material.
  12223. *
  12224. * @tsl
  12225. * @type {Node<vec3>}
  12226. */
  12227. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  12228. /**
  12229. * TSL object that represents the specular intensity of the current material.
  12230. * The value is composed via `specularIntensity` * `specularMap.a`.
  12231. *
  12232. * @tsl
  12233. * @type {Node<float>}
  12234. */
  12235. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  12236. /**
  12237. * TSL object that represents the specular color of the current material.
  12238. * The value is composed via `specularColor` * `specularMap.rgb`.
  12239. *
  12240. * @tsl
  12241. * @type {Node<vec3>}
  12242. */
  12243. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  12244. /**
  12245. * TSL object that represents the specular strength of the current material.
  12246. * The value is composed via `specularMap.r`.
  12247. *
  12248. * @tsl
  12249. * @type {Node<float>}
  12250. */
  12251. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  12252. /**
  12253. * TSL object that represents the reflectivity of the current material.
  12254. *
  12255. * @tsl
  12256. * @type {Node<float>}
  12257. */
  12258. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  12259. /**
  12260. * TSL object that represents the roughness of the current material.
  12261. * The value is composed via `roughness` * `roughnessMap.g`.
  12262. *
  12263. * @tsl
  12264. * @type {Node<float>}
  12265. */
  12266. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  12267. /**
  12268. * TSL object that represents the metalness of the current material.
  12269. * The value is composed via `metalness` * `metalnessMap.b`.
  12270. *
  12271. * @tsl
  12272. * @type {Node<float>}
  12273. */
  12274. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  12275. /**
  12276. * TSL object that represents the normal of the current material.
  12277. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  12278. *
  12279. * @tsl
  12280. * @type {Node<vec3>}
  12281. */
  12282. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  12283. /**
  12284. * TSL object that represents the clearcoat of the current material.
  12285. * The value is composed via `clearcoat` * `clearcoatMap.r`
  12286. *
  12287. * @tsl
  12288. * @type {Node<float>}
  12289. */
  12290. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  12291. /**
  12292. * TSL object that represents the clearcoat roughness of the current material.
  12293. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  12294. *
  12295. * @tsl
  12296. * @type {Node<float>}
  12297. */
  12298. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  12299. /**
  12300. * TSL object that represents the clearcoat normal of the current material.
  12301. * The value will be either `clearcoatNormalMap` or `normalView`.
  12302. *
  12303. * @tsl
  12304. * @type {Node<vec3>}
  12305. */
  12306. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  12307. /**
  12308. * TSL object that represents the rotation of the current sprite material.
  12309. *
  12310. * @tsl
  12311. * @type {Node<float>}
  12312. */
  12313. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  12314. /**
  12315. * TSL object that represents the sheen color of the current material.
  12316. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  12317. *
  12318. * @tsl
  12319. * @type {Node<vec3>}
  12320. */
  12321. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  12322. /**
  12323. * TSL object that represents the sheen roughness of the current material.
  12324. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  12325. *
  12326. * @tsl
  12327. * @type {Node<float>}
  12328. */
  12329. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  12330. /**
  12331. * TSL object that represents the anisotropy of the current material.
  12332. *
  12333. * @tsl
  12334. * @type {Node<vec2>}
  12335. */
  12336. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  12337. /**
  12338. * TSL object that represents the iridescence of the current material.
  12339. *
  12340. * @tsl
  12341. * @type {Node<float>}
  12342. */
  12343. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  12344. /**
  12345. * TSL object that represents the iridescence IOR of the current material.
  12346. *
  12347. * @tsl
  12348. * @type {Node<float>}
  12349. */
  12350. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  12351. /**
  12352. * TSL object that represents the iridescence thickness of the current material.
  12353. *
  12354. * @tsl
  12355. * @type {Node<float>}
  12356. */
  12357. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  12358. /**
  12359. * TSL object that represents the transmission of the current material.
  12360. * The value is composed via `transmission` * `transmissionMap.r`.
  12361. *
  12362. * @tsl
  12363. * @type {Node<float>}
  12364. */
  12365. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  12366. /**
  12367. * TSL object that represents the thickness of the current material.
  12368. * The value is composed via `thickness` * `thicknessMap.g`.
  12369. *
  12370. * @tsl
  12371. * @type {Node<float>}
  12372. */
  12373. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  12374. /**
  12375. * TSL object that represents the IOR of the current material.
  12376. *
  12377. * @tsl
  12378. * @type {Node<float>}
  12379. */
  12380. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  12381. /**
  12382. * TSL object that represents the attenuation distance of the current material.
  12383. *
  12384. * @tsl
  12385. * @type {Node<float>}
  12386. */
  12387. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  12388. /**
  12389. * TSL object that represents the attenuation color of the current material.
  12390. *
  12391. * @tsl
  12392. * @type {Node<vec3>}
  12393. */
  12394. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  12395. /**
  12396. * TSL object that represents the scale of the current dashed line material.
  12397. *
  12398. * @tsl
  12399. * @type {Node<float>}
  12400. */
  12401. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  12402. /**
  12403. * TSL object that represents the dash size of the current dashed line material.
  12404. *
  12405. * @tsl
  12406. * @type {Node<float>}
  12407. */
  12408. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  12409. /**
  12410. * TSL object that represents the gap size of the current dashed line material.
  12411. *
  12412. * @tsl
  12413. * @type {Node<float>}
  12414. */
  12415. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  12416. /**
  12417. * TSL object that represents the line width of the current line material.
  12418. *
  12419. * @tsl
  12420. * @type {Node<float>}
  12421. */
  12422. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  12423. /**
  12424. * TSL object that represents the dash offset of the current line material.
  12425. *
  12426. * @tsl
  12427. * @type {Node<float>}
  12428. */
  12429. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  12430. /**
  12431. * TSL object that represents the point size of the current points material.
  12432. *
  12433. * @tsl
  12434. * @type {Node<float>}
  12435. */
  12436. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  12437. /**
  12438. * TSL object that represents the dispersion of the current material.
  12439. *
  12440. * @tsl
  12441. * @type {Node<float>}
  12442. */
  12443. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  12444. /**
  12445. * TSL object that represents the retroreflective strength of the current material.
  12446. *
  12447. * @tsl
  12448. * @type {Node<float>}
  12449. */
  12450. const materialRetroreflective = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.RETROREFLECTIVE );
  12451. /**
  12452. * TSL object that represents the light map of the current material.
  12453. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  12454. *
  12455. * @tsl
  12456. * @type {Node<vec3>}
  12457. */
  12458. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  12459. /**
  12460. * TSL object that represents the ambient occlusion map of the current material.
  12461. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  12462. *
  12463. * @tsl
  12464. * @type {Node<float>}
  12465. */
  12466. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  12467. /**
  12468. * TSL object that represents the anisotropy vector of the current material.
  12469. *
  12470. * @tsl
  12471. * @type {Node<vec2>}
  12472. */
  12473. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  12474. return frame.material;
  12475. } ).onRenderUpdate( function ( { material } ) {
  12476. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  12477. } );
  12478. /**
  12479. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  12480. *
  12481. * @tsl
  12482. * @type {VaryingNode<vec4>}
  12483. */
  12484. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  12485. return builder.context.setupModelViewProjection();
  12486. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  12487. /**
  12488. * EventNode is a node that executes a callback during specific update phases.
  12489. *
  12490. * @augments Node
  12491. */
  12492. class EventNode extends Node {
  12493. static get type() {
  12494. return 'EventNode';
  12495. }
  12496. /**
  12497. * Creates an EventNode.
  12498. *
  12499. * @param {string} eventType - The type of event
  12500. * @param {Function} callback - The callback to execute on update.
  12501. */
  12502. constructor( eventType, callback ) {
  12503. super( 'void' );
  12504. this.eventType = eventType;
  12505. this.callback = callback;
  12506. if ( eventType === EventNode.OBJECT ) {
  12507. this.updateType = NodeUpdateType.OBJECT;
  12508. } else if ( eventType === EventNode.MATERIAL ) {
  12509. this.updateType = NodeUpdateType.RENDER;
  12510. } else if ( eventType === EventNode.FRAME ) {
  12511. this.updateType = NodeUpdateType.FRAME;
  12512. } else if ( eventType === EventNode.BEFORE_OBJECT ) {
  12513. this.updateBeforeType = NodeUpdateType.OBJECT;
  12514. } else if ( eventType === EventNode.BEFORE_MATERIAL ) {
  12515. this.updateBeforeType = NodeUpdateType.RENDER;
  12516. } else if ( eventType === EventNode.BEFORE_FRAME ) {
  12517. this.updateBeforeType = NodeUpdateType.FRAME;
  12518. }
  12519. }
  12520. update( frame ) {
  12521. this.callback( frame );
  12522. }
  12523. updateBefore( frame ) {
  12524. this.callback( frame );
  12525. }
  12526. }
  12527. EventNode.OBJECT = 'object';
  12528. EventNode.MATERIAL = 'material';
  12529. EventNode.FRAME = 'frame';
  12530. EventNode.BEFORE_OBJECT = 'beforeObject';
  12531. EventNode.BEFORE_MATERIAL = 'beforeMaterial';
  12532. EventNode.BEFORE_FRAME = 'beforeFrame';
  12533. /**
  12534. * Helper to create an EventNode and add it to the stack.
  12535. *
  12536. * @param {string} type - The event type.
  12537. * @param {Function} callback - The callback function.
  12538. * @returns {EventNode}
  12539. */
  12540. const createEvent = ( type, callback ) => new EventNode( type, callback ).toStack();
  12541. /**
  12542. * Creates an event that triggers a function every time an object (Mesh|Sprite) is rendered.
  12543. *
  12544. * The event will be bound to the declared TSL function `Fn()`; it must be declared within a `Fn()` or the JS function call must be inherited from one.
  12545. *
  12546. * @param {Function} callback - The callback function.
  12547. * @returns {EventNode}
  12548. */
  12549. const OnObjectUpdate = ( callback ) => createEvent( EventNode.OBJECT, callback );
  12550. /**
  12551. * Creates an event that triggers a function when the first object that uses the material is rendered.
  12552. *
  12553. * The event will be bound to the declared TSL function `Fn()`; it must be declared within a `Fn()` or the JS function call must be inherited from one.
  12554. *
  12555. * @param {Function} callback - The callback function.
  12556. * @returns {EventNode}
  12557. */
  12558. const OnMaterialUpdate = ( callback ) => createEvent( EventNode.MATERIAL, callback );
  12559. /**
  12560. * Creates an event that triggers a function every frame.
  12561. *
  12562. * The event will be bound to the declared TSL function `Fn()`; it must be declared within a `Fn()` or the JS function call must be inherited from one.
  12563. *
  12564. * @param {Function} callback - The callback function.
  12565. * @returns {EventNode}
  12566. */
  12567. const OnFrameUpdate = ( callback ) => createEvent( EventNode.FRAME, callback );
  12568. /**
  12569. * Creates an event that triggers a function before an object (Mesh|Sprite) is updated.
  12570. *
  12571. * The event will be bound to the declared TSL function `Fn()`; it must be declared within a `Fn()` or the JS function call must be inherited from one.
  12572. *
  12573. * @param {Function} callback - The callback function.
  12574. * @returns {EventNode}
  12575. */
  12576. const OnBeforeObjectUpdate = ( callback ) => createEvent( EventNode.BEFORE_OBJECT, callback );
  12577. /**
  12578. * Creates an event that triggers a function before the material is updated.
  12579. *
  12580. * The event will be bound to the declared TSL function `Fn()`; it must be declared within a `Fn()` or the JS function call must be inherited from one.
  12581. *
  12582. * @param {Function} callback - The callback function.
  12583. * @returns {EventNode}
  12584. */
  12585. const OnBeforeMaterialUpdate = ( callback ) => createEvent( EventNode.BEFORE_MATERIAL, callback );
  12586. /**
  12587. * Creates an event that triggers a function before every frame.
  12588. *
  12589. * The event will be bound to the declared TSL function `Fn()`; it must be declared within a `Fn()` or the JS function call must be inherited from one.
  12590. *
  12591. * @param {Function} callback - The callback function.
  12592. * @returns {EventNode}
  12593. */
  12594. const OnBeforeFrameUpdate = ( callback ) => createEvent( EventNode.BEFORE_FRAME, callback );
  12595. /**
  12596. * This class enables element access on instances of {@link StorageBufferNode}.
  12597. * In most cases, it is indirectly used when accessing elements with the
  12598. * {@link StorageBufferNode#element} method.
  12599. *
  12600. * ```js
  12601. * const position = positionStorage.element( instanceIndex );
  12602. * ```
  12603. *
  12604. * @augments ArrayElementNode
  12605. */
  12606. class StorageArrayElementNode extends ArrayElementNode {
  12607. static get type() {
  12608. return 'StorageArrayElementNode';
  12609. }
  12610. /**
  12611. * Constructs storage buffer element node.
  12612. *
  12613. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  12614. * @param {Node} indexNode - The index node that defines the element access.
  12615. */
  12616. constructor( storageBufferNode, indexNode ) {
  12617. super( storageBufferNode, indexNode );
  12618. /**
  12619. * This flag can be used for type testing.
  12620. *
  12621. * @type {boolean}
  12622. * @readonly
  12623. * @default true
  12624. */
  12625. this.isStorageArrayElementNode = true;
  12626. }
  12627. /**
  12628. * The storage buffer node.
  12629. *
  12630. * @param {Node} value
  12631. * @type {StorageBufferNode}
  12632. */
  12633. set storageBufferNode( value ) {
  12634. this.node = value;
  12635. }
  12636. get storageBufferNode() {
  12637. return this.node;
  12638. }
  12639. getMemberType( builder, name ) {
  12640. const structTypeNode = this.storageBufferNode.structTypeNode;
  12641. if ( structTypeNode ) {
  12642. return structTypeNode.getMemberType( builder, name );
  12643. }
  12644. return 'void';
  12645. }
  12646. setup( builder ) {
  12647. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  12648. if ( this.node.isPBO === true ) {
  12649. builder.setupPBO( this.node );
  12650. }
  12651. }
  12652. return super.setup( builder );
  12653. }
  12654. generate( builder, output ) {
  12655. let snippet;
  12656. const isAssignContext = builder.isContextAssign();
  12657. //
  12658. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  12659. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  12660. snippet = builder.generatePBO( this );
  12661. } else {
  12662. snippet = this.node.build( builder );
  12663. }
  12664. } else {
  12665. snippet = super.generate( builder );
  12666. }
  12667. if ( isAssignContext !== true ) {
  12668. const type = this.getNodeType( builder );
  12669. snippet = builder.format( snippet, type, output );
  12670. }
  12671. return snippet;
  12672. }
  12673. }
  12674. /**
  12675. * TSL function for creating a storage element node.
  12676. *
  12677. * @tsl
  12678. * @function
  12679. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  12680. * @param {Node} indexNode - The index node that defines the element access.
  12681. * @returns {StorageArrayElementNode}
  12682. */
  12683. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode ).setParameterLength( 2 );
  12684. /**
  12685. * This node is used in context of compute shaders and allows to define a
  12686. * storage buffer for data. A typical workflow is to create instances of
  12687. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  12688. * setup up a compute shader that writes into the buffers and then convert
  12689. * the storage buffers to attribute nodes for rendering.
  12690. *
  12691. * ```js
  12692. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  12693. *
  12694. * const computeInit = Fn( () => { // the compute shader
  12695. *
  12696. * const position = positionBuffer.element( instanceIndex );
  12697. *
  12698. * // compute position data
  12699. *
  12700. * position.x = 1;
  12701. * position.y = 1;
  12702. * position.z = 1;
  12703. *
  12704. * } )().compute( particleCount );
  12705. *
  12706. * const particleMaterial = new THREE.SpriteNodeMaterial();
  12707. * particleMaterial.positionNode = positionBuffer.toAttribute();
  12708. *
  12709. * renderer.computeAsync( computeInit );
  12710. *
  12711. * ```
  12712. *
  12713. * @augments BufferNode
  12714. */
  12715. class StorageBufferNode extends BufferNode {
  12716. static get type() {
  12717. return 'StorageBufferNode';
  12718. }
  12719. /**
  12720. * Constructs a new storage buffer node.
  12721. *
  12722. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  12723. * @param {?(string|Struct)} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  12724. * @param {number} [bufferCount=0] - The buffer count.
  12725. */
  12726. constructor( value, bufferType = null, bufferCount = 0 ) {
  12727. let nodeType, structTypeNode = null;
  12728. if ( bufferType && bufferType.isStructTypeNode ) {
  12729. nodeType = 'struct';
  12730. structTypeNode = bufferType;
  12731. if ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) {
  12732. bufferCount = value.count;
  12733. }
  12734. } else if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  12735. nodeType = getTypeFromLength( value.itemSize );
  12736. bufferCount = value.count;
  12737. } else {
  12738. nodeType = bufferType;
  12739. }
  12740. super( value, nodeType, bufferCount );
  12741. /**
  12742. * This flag can be used for type testing.
  12743. *
  12744. * @type {boolean}
  12745. * @readonly
  12746. * @default true
  12747. */
  12748. this.isStorageBufferNode = true;
  12749. /**
  12750. * The buffer struct type.
  12751. *
  12752. * @type {?StructTypeNode}
  12753. * @default null
  12754. */
  12755. this.structTypeNode = structTypeNode;
  12756. /**
  12757. * The access type of the texture node.
  12758. *
  12759. * @type {string}
  12760. * @default 'readWrite'
  12761. */
  12762. this.access = NodeAccess.READ_WRITE;
  12763. /**
  12764. * Whether the node is atomic or not.
  12765. *
  12766. * @type {boolean}
  12767. * @default false
  12768. */
  12769. this.isAtomic = false;
  12770. /**
  12771. * Whether the node represents a PBO or not.
  12772. * Only relevant for WebGL.
  12773. *
  12774. * @type {boolean}
  12775. * @default false
  12776. */
  12777. this.isPBO = false;
  12778. /**
  12779. * A reference to the internal buffer attribute node.
  12780. *
  12781. * @private
  12782. * @type {?BufferAttributeNode}
  12783. * @default null
  12784. */
  12785. this._attribute = null;
  12786. /**
  12787. * A reference to the internal varying node.
  12788. *
  12789. * @private
  12790. * @type {?VaryingNode}
  12791. * @default null
  12792. */
  12793. this._varying = null;
  12794. /**
  12795. * `StorageBufferNode` sets this property to `true` by default.
  12796. *
  12797. * @type {boolean}
  12798. * @default true
  12799. */
  12800. this.global = true;
  12801. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  12802. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  12803. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  12804. else value.isStorageBufferAttribute = true;
  12805. }
  12806. }
  12807. /**
  12808. * This method is overwritten since the buffer data might be shared
  12809. * and thus the hash should be shared as well.
  12810. *
  12811. * @param {NodeBuilder} builder - The current node builder.
  12812. * @return {string} The hash.
  12813. */
  12814. getHash( builder ) {
  12815. let id;
  12816. if ( this.bufferCount === 0 ) {
  12817. let bufferData = builder.globalCache.getData( this.value );
  12818. if ( bufferData === undefined ) {
  12819. bufferData = {
  12820. node: this
  12821. };
  12822. builder.globalCache.setData( this.value, bufferData );
  12823. }
  12824. id = bufferData.node.id;
  12825. } else {
  12826. id = this.id;
  12827. }
  12828. return String( id );
  12829. }
  12830. /**
  12831. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  12832. *
  12833. * @param {NodeBuilder} builder - The current node builder.
  12834. * @return {string} The input type.
  12835. */
  12836. getInputType( /*builder*/ ) {
  12837. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  12838. }
  12839. /**
  12840. * Enables element access with the given index node.
  12841. *
  12842. * @param {IndexNode} indexNode - The index node.
  12843. * @return {StorageArrayElementNode} A node representing the element access.
  12844. */
  12845. element( indexNode ) {
  12846. return storageElement( this, indexNode );
  12847. }
  12848. /**
  12849. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  12850. *
  12851. * @param {boolean} value - The value so set.
  12852. * @return {StorageBufferNode} A reference to this node.
  12853. */
  12854. setPBO( value ) {
  12855. this.isPBO = value;
  12856. return this;
  12857. }
  12858. /**
  12859. * Returns the `isPBO` value.
  12860. *
  12861. * @return {boolean} Whether the node represents a PBO or not.
  12862. */
  12863. getPBO() {
  12864. return this.isPBO;
  12865. }
  12866. /**
  12867. * Defines the node access.
  12868. *
  12869. * @param {string} value - The node access.
  12870. * @return {StorageBufferNode} A reference to this node.
  12871. */
  12872. setAccess( value ) {
  12873. this.access = value;
  12874. return this;
  12875. }
  12876. /**
  12877. * Convenience method for configuring a read-only node access.
  12878. *
  12879. * @return {StorageBufferNode} A reference to this node.
  12880. */
  12881. toReadOnly() {
  12882. return this.setAccess( NodeAccess.READ_ONLY );
  12883. }
  12884. /**
  12885. * Defines whether the node is atomic or not.
  12886. *
  12887. * @param {boolean} value - The atomic flag.
  12888. * @return {StorageBufferNode} A reference to this node.
  12889. */
  12890. setAtomic( value ) {
  12891. this.isAtomic = value;
  12892. return this;
  12893. }
  12894. /**
  12895. * Convenience method for making this node atomic.
  12896. *
  12897. * @return {StorageBufferNode} A reference to this node.
  12898. */
  12899. toAtomic() {
  12900. return this.setAtomic( true );
  12901. }
  12902. /**
  12903. * Returns attribute data for this storage buffer node.
  12904. *
  12905. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  12906. */
  12907. getAttributeData() {
  12908. if ( this._attribute === null ) {
  12909. this._attribute = bufferAttribute( this.value );
  12910. this._varying = varying( this._attribute );
  12911. }
  12912. return {
  12913. attribute: this._attribute,
  12914. varying: this._varying
  12915. };
  12916. }
  12917. /**
  12918. * This method is overwritten since the node type from the availability of storage buffers
  12919. * and the attribute data.
  12920. *
  12921. * @param {NodeBuilder} builder - The current node builder.
  12922. * @return {string} The node type.
  12923. */
  12924. generateNodeType( builder ) {
  12925. if ( this.structTypeNode !== null ) {
  12926. return this.structTypeNode.getNodeType( builder );
  12927. }
  12928. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  12929. return super.generateNodeType( builder );
  12930. }
  12931. const { attribute } = this.getAttributeData();
  12932. return attribute.getNodeType( builder );
  12933. }
  12934. /**
  12935. * Returns the type of a member of the struct.
  12936. *
  12937. * @param {NodeBuilder} builder - The current node builder.
  12938. * @param {string} name - The name of the member.
  12939. * @return {string} The type of the member.
  12940. */
  12941. getMemberType( builder, name ) {
  12942. if ( this.structTypeNode !== null ) {
  12943. return this.structTypeNode.getMemberType( builder, name );
  12944. }
  12945. return 'void';
  12946. }
  12947. /**
  12948. * Generates the code snippet of the storage buffer node.
  12949. *
  12950. * @param {NodeBuilder} builder - The current node builder.
  12951. * @return {string} The generated code snippet.
  12952. */
  12953. generate( builder ) {
  12954. if ( this.structTypeNode !== null ) this.structTypeNode.build( builder );
  12955. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  12956. return super.generate( builder );
  12957. }
  12958. const { attribute, varying } = this.getAttributeData();
  12959. const output = varying.build( builder );
  12960. builder.registerTransform( output, attribute );
  12961. return output;
  12962. }
  12963. }
  12964. /**
  12965. * TSL function for creating a storage buffer node.
  12966. *
  12967. * @tsl
  12968. * @function
  12969. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  12970. * @param {?(string|Struct)} [type=null] - The buffer type (e.g. `'vec3'`).
  12971. * @param {number} [count=0] - The buffer count.
  12972. * @returns {StorageBufferNode}
  12973. */
  12974. const storage = ( value, type = null, count = 0 ) => new StorageBufferNode( value, type, count );
  12975. const _matrixBuffers = /*@__PURE__*/ new WeakMap();
  12976. const _colorBuffers = /*@__PURE__*/ new WeakMap();
  12977. const _previousInstanceMatrices = /*@__PURE__*/ new WeakMap();
  12978. /**
  12979. * Creates the appropriate node for instanced matrix transformations.
  12980. * Depending on buffer limits and storage capability, returns either a storage, buffer, or instanced interleaved attribute node.
  12981. *
  12982. * @param {NodeBuilder} builder - The current node builder.
  12983. * @param {InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceMatrix - The matrix buffer attribute.
  12984. * @returns {Node} The matrix node.
  12985. */
  12986. function createInstanceMatrixNode( builder, instanceMatrix ) {
  12987. let instanceMatrixNode;
  12988. const matrixCount = Math.max( instanceMatrix.count, 1 );
  12989. const isStorageMatrix = instanceMatrix.isStorageInstancedBufferAttribute === true;
  12990. if ( isStorageMatrix ) {
  12991. instanceMatrixNode = storage( instanceMatrix, 'mat4', matrixCount ).element( instanceIndex );
  12992. } else {
  12993. const uniformBufferSize = matrixCount * 16 * 4;
  12994. if ( uniformBufferSize <= builder.getUniformBufferLimit() ) {
  12995. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', matrixCount ).element( instanceIndex );
  12996. } else {
  12997. let interleaved = _matrixBuffers.get( instanceMatrix );
  12998. if ( ! interleaved ) {
  12999. interleaved = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  13000. _matrixBuffers.set( instanceMatrix, interleaved );
  13001. }
  13002. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  13003. const instanceBuffers = [
  13004. bufferFn( interleaved, 'vec4', 16, 0 ),
  13005. bufferFn( interleaved, 'vec4', 16, 4 ),
  13006. bufferFn( interleaved, 'vec4', 16, 8 ),
  13007. bufferFn( interleaved, 'vec4', 16, 12 )
  13008. ];
  13009. instanceMatrixNode = mat4( ...instanceBuffers );
  13010. }
  13011. }
  13012. return instanceMatrixNode;
  13013. }
  13014. /**
  13015. * Retrieves or initializes the previous frame instance matrix node for motion vectors.
  13016. * Uses a WeakMap to cache previous frame instance matrices and their TSL nodes.
  13017. *
  13018. * @param {InstancedMesh} instancedMesh - The instanced mesh object.
  13019. * @param {InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceMatrix - The current matrix buffer attribute.
  13020. * @param {NodeBuilder} builder - The current node builder.
  13021. * @returns {Node} The previous frame instance matrix node.
  13022. */
  13023. function getPreviousInstance( instancedMesh, instanceMatrix, builder ) {
  13024. let data = _previousInstanceMatrices.get( instancedMesh );
  13025. if ( data === undefined ) {
  13026. const previousInstanceMatrix = instanceMatrix.clone();
  13027. data = {
  13028. previousInstanceMatrix,
  13029. node: createInstanceMatrixNode( builder, previousInstanceMatrix )
  13030. };
  13031. _previousInstanceMatrices.set( instancedMesh, data );
  13032. }
  13033. return data.node;
  13034. }
  13035. /**
  13036. * TSL object representing a varying property for the instanced color vector.
  13037. *
  13038. * @type {VaryingNode<vec3>}
  13039. */
  13040. const instanceColor = /*@__PURE__*/ varyingProperty( 'vec3', 'vInstanceColor' );
  13041. /**
  13042. * TSL function representing the standard instancing vertex shader setup.
  13043. * Transforms positionLocal and normalLocal, and assigns varying color in-place.
  13044. *
  13045. * @tsl
  13046. * @function
  13047. * @param {InstancedBufferAttribute|StorageInstancedBufferAttribute} matrices - The instanced transformation matrices.
  13048. * @param {?InstancedBufferAttribute|StorageInstancedBufferAttribute} [colors=null] - The optional instanced colors.
  13049. */
  13050. const instance = /*@__PURE__*/ Fn( ( [ matrices, colors = null ], builder ) => {
  13051. const isStorageMatrix = matrices.isStorageInstancedBufferAttribute === true;
  13052. const isStorageColor = colors && colors.isStorageInstancedBufferAttribute === true;
  13053. const instanceMatrixNode = createInstanceMatrixNode( builder, matrices );
  13054. // interleaved buffer tracking for matrix
  13055. let interleavedMatrix = null;
  13056. if ( ! isStorageMatrix ) {
  13057. const uniformBufferSize = Math.max( matrices.count, 1 ) * 16 * 4;
  13058. if ( uniformBufferSize > builder.getUniformBufferLimit() ) {
  13059. interleavedMatrix = _matrixBuffers.get( matrices );
  13060. }
  13061. }
  13062. let instanceColorNode = null;
  13063. let interleavedColor = null;
  13064. if ( colors ) {
  13065. if ( isStorageColor ) {
  13066. instanceColorNode = storage( colors, 'vec3', Math.max( colors.count, 1 ) ).element( instanceIndex );
  13067. } else {
  13068. let bufferAttribute = _colorBuffers.get( colors );
  13069. if ( ! bufferAttribute ) {
  13070. bufferAttribute = new InstancedBufferAttribute( colors.array, 3 );
  13071. _colorBuffers.set( colors, bufferAttribute );
  13072. }
  13073. interleavedColor = bufferAttribute;
  13074. const bufferFn = colors.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  13075. instanceColorNode = vec3( bufferFn( bufferAttribute, 'vec3', 3, 0 ) );
  13076. }
  13077. }
  13078. // Synchronization of dynamic buffer updates per frame
  13079. if ( interleavedMatrix !== null || interleavedColor !== null ) {
  13080. OnFrameUpdate( () => {
  13081. if ( interleavedMatrix !== null ) {
  13082. interleavedMatrix.clearUpdateRanges();
  13083. interleavedMatrix.updateRanges.push( ...matrices.updateRanges );
  13084. if ( matrices.version !== interleavedMatrix.version ) {
  13085. interleavedMatrix.version = matrices.version;
  13086. }
  13087. }
  13088. if ( colors && interleavedColor !== null ) {
  13089. interleavedColor.clearUpdateRanges();
  13090. interleavedColor.updateRanges.push( ...colors.updateRanges );
  13091. if ( colors.version !== interleavedColor.version ) {
  13092. interleavedColor.version = colors.version;
  13093. }
  13094. }
  13095. } );
  13096. }
  13097. // POSITION
  13098. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  13099. positionLocal.assign( instancePosition );
  13100. if ( builder.needsPreviousData() ) {
  13101. const instancedMesh = builder.object;
  13102. OnObjectUpdate( ( { object } ) => {
  13103. const previousInstanceData = _previousInstanceMatrices.get( object );
  13104. previousInstanceData.previousInstanceMatrix.array.set( matrices.array );
  13105. } );
  13106. const previousInstanceMatrixNode = getPreviousInstance( instancedMesh, matrices, builder );
  13107. positionPrevious.assign( previousInstanceMatrixNode.mul( positionPrevious ).xyz );
  13108. }
  13109. // NORMAL
  13110. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  13111. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  13112. normalLocal.assign( instanceNormal );
  13113. }
  13114. // COLOR
  13115. if ( instanceColorNode !== null ) {
  13116. instanceColor.assign( instanceColorNode );
  13117. }
  13118. }, 'void' );
  13119. /**
  13120. * TSL wrapper for applying instanced mesh rendering setup.
  13121. *
  13122. * @tsl
  13123. * @function
  13124. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  13125. */
  13126. const instancedMesh = /*@__PURE__*/ Fn( ( [ instancedMesh ] ) => {
  13127. const { instanceMatrix, instanceColor } = instancedMesh;
  13128. instance( instanceMatrix, instanceColor );
  13129. }, 'void' );
  13130. /**
  13131. * TSL function that retrieves the batching color for a given instance ID from a colors texture.
  13132. *
  13133. * @param {Node<texture>} colorsTexture - The colors texture.
  13134. * @param {Node<int>} id - The instance or batch ID.
  13135. * @returns {Node<vec4>} The retrieved color.
  13136. */
  13137. const getBatchingColor = /*@__PURE__*/ Fn( ( [ colorsTexture, id ] ) => {
  13138. const size = int( textureSize( textureLoad( colorsTexture ), 0 ).x ).toConst();
  13139. const j = int( id );
  13140. const x = j.mod( size ).toConst();
  13141. const y = j.div( size ).toConst();
  13142. return textureLoad( colorsTexture, ivec2( x, y ) );
  13143. } );
  13144. /**
  13145. * TSL function that retrieves the indirect index for a given batch ID.
  13146. *
  13147. * @param {BatchedMesh} batchMesh - The batched mesh.
  13148. * @param {Node<int>} id - The draw or instance ID.
  13149. * @returns {Node<uint>} The indirect index.
  13150. */
  13151. const getIndirectIndex = /*@__PURE__*/ Fn( ( [ indirectTexture, id ] ) => {
  13152. const size = int( textureSize( textureLoad( indirectTexture ), 0 ).x ).toConst();
  13153. const x = int( id ).mod( size ).toConst();
  13154. const y = int( id ).div( size ).toConst();
  13155. return textureLoad( indirectTexture, ivec2( x, y ) ).x;
  13156. } );
  13157. /**
  13158. * TSL object representing a varying property for the batching color vector.
  13159. *
  13160. * @type {VaryingNode<vec4>}
  13161. */
  13162. const batchColor = /*@__PURE__*/ varyingProperty( 'vec4', 'vBatchColor' );
  13163. /**
  13164. * TSL function representing the vertex shader batching setup.
  13165. * Applies the batch transformation matrix to positionLocal, normalLocal, and tangentLocal.
  13166. * Also assigns the batch color if a color texture is present.
  13167. *
  13168. * @tsl
  13169. * @function
  13170. * @param {BatchedMesh} batchMesh - The batched mesh.
  13171. */
  13172. const batch = /*@__PURE__*/ Fn( ( [ batchMesh ], builder ) => {
  13173. const batchingIdNode = builder.getDrawIndex() === null ? instanceIndex : drawIndex;
  13174. const indirectId = getIndirectIndex( batchMesh._indirectTexture, int( batchingIdNode ) );
  13175. const matricesTexture = batchMesh._matricesTexture;
  13176. const size = int( textureSize( textureLoad( matricesTexture ), 0 ).x ).toConst();
  13177. const j = float( indirectId ).mul( 4 ).toInt().toConst();
  13178. const x = j.mod( size ).toConst();
  13179. const y = j.div( size ).toConst();
  13180. const batchingMatrix = mat4(
  13181. textureLoad( matricesTexture, ivec2( x, y ) ),
  13182. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  13183. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  13184. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  13185. );
  13186. const colorsTexture = batchMesh._colorsTexture;
  13187. if ( colorsTexture !== null ) {
  13188. const color = getBatchingColor( colorsTexture, indirectId );
  13189. batchColor.assign( color );
  13190. }
  13191. const bm = mat3( batchingMatrix );
  13192. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  13193. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  13194. const batchingNormal = bm.mul( transformedNormal ).xyz;
  13195. normalLocal.assign( batchingNormal );
  13196. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  13197. tangentLocal.mulAssign( bm );
  13198. }
  13199. }, 'void' );
  13200. const _skeletonsUpdated = /*@__PURE__*/ new WeakMap();
  13201. const _previousBoneMatricesData = /*@__PURE__*/ new WeakMap();
  13202. /**
  13203. * Computes the skinned position by applying bone matrices based on weights.
  13204. *
  13205. * @param {Node} boneMatrices - The bone matrices buffer or storage node.
  13206. * @param {Node<vec3>} position - The vertex position to transform.
  13207. * @param {Node<mat4>} bindMatrix - The bind matrix node.
  13208. * @param {Node<mat4>} bindMatrixInverse - The inverse bind matrix node.
  13209. * @param {Node<uvec4>} skinIndex - The skin index attribute.
  13210. * @param {Node<vec4>} skinWeight - The skin weight attribute.
  13211. * @returns {Node<vec3>} The skinned position.
  13212. */
  13213. function getSkinnedPosition( boneMatrices, position, bindMatrix, bindMatrixInverse, skinIndex, skinWeight ) {
  13214. const boneMatX = boneMatrices.element( skinIndex.x );
  13215. const boneMatY = boneMatrices.element( skinIndex.y );
  13216. const boneMatZ = boneMatrices.element( skinIndex.z );
  13217. const boneMatW = boneMatrices.element( skinIndex.w );
  13218. // POSITION
  13219. const skinVertex = bindMatrix.mul( position );
  13220. const skinned = add(
  13221. boneMatX.mul( skinWeight.x ).mul( skinVertex ),
  13222. boneMatY.mul( skinWeight.y ).mul( skinVertex ),
  13223. boneMatZ.mul( skinWeight.z ).mul( skinVertex ),
  13224. boneMatW.mul( skinWeight.w ).mul( skinVertex )
  13225. );
  13226. return bindMatrixInverse.mul( skinned ).xyz;
  13227. }
  13228. /**
  13229. * Computes the skinned normal and tangent vectors by applying bone matrices based on weights.
  13230. *
  13231. * @param {Node} boneMatrices - The bone matrices buffer or storage node.
  13232. * @param {Node<vec3>} normal - The normal vector in local space.
  13233. * @param {Node<vec3>} tangent - The tangent vector in local space.
  13234. * @param {Node<mat4>} bindMatrix - The bind matrix node.
  13235. * @param {Node<mat4>} bindMatrixInverse - The inverse bind matrix node.
  13236. * @param {Node<uvec4>} skinIndex - The skin index attribute.
  13237. * @param {Node<vec4>} skinWeight - The skin weight attribute.
  13238. * @returns {{skinNormal: Node<vec3>, skinTangent: Node<vec3>}} The skinned normal and tangent.
  13239. */
  13240. function getSkinnedNormalAndTangent( boneMatrices, normal, tangent, bindMatrix, bindMatrixInverse, skinIndex, skinWeight ) {
  13241. const boneMatX = boneMatrices.element( skinIndex.x );
  13242. const boneMatY = boneMatrices.element( skinIndex.y );
  13243. const boneMatZ = boneMatrices.element( skinIndex.z );
  13244. const boneMatW = boneMatrices.element( skinIndex.w );
  13245. // NORMAL and TANGENT
  13246. let skinMatrix = add(
  13247. skinWeight.x.mul( boneMatX ),
  13248. skinWeight.y.mul( boneMatY ),
  13249. skinWeight.z.mul( boneMatZ ),
  13250. skinWeight.w.mul( boneMatW )
  13251. );
  13252. skinMatrix = bindMatrixInverse.mul( skinMatrix ).mul( bindMatrix );
  13253. const skinMatrix3 = mat3( skinMatrix );
  13254. const skinNormal = skinMatrix3.mul( normal );
  13255. const skinTangent = skinMatrix3.mul( tangent );
  13256. return { skinNormal, skinTangent };
  13257. }
  13258. /**
  13259. * Retrieves or initializes the previous frame skinned position node for motion vectors.
  13260. * Uses a WeakMap to cache previous frame bone matrix arrays and their TSL buffer nodes.
  13261. *
  13262. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  13263. * @param {Node<mat4>} bindMatrixNode - The bind matrix node.
  13264. * @param {Node<mat4>} bindMatrixInverseNode - The inverse bind matrix node.
  13265. * @param {Node<uvec4>} skinIndexNode - The skin index attribute.
  13266. * @param {Node<vec4>} skinWeightNode - The skin weight attribute.
  13267. * @returns {Node<vec3>} The skinned position from the previous frame.
  13268. */
  13269. function getPreviousSkinnedPosition( skinnedMesh, bindMatrixNode, bindMatrixInverseNode, skinIndexNode, skinWeightNode ) {
  13270. const skeleton = skinnedMesh.skeleton;
  13271. let data = _previousBoneMatricesData.get( skeleton );
  13272. if ( data === undefined ) {
  13273. skeleton.update();
  13274. const previousBoneMatrices = new Float32Array( skeleton.boneMatrices );
  13275. data = {
  13276. previousBoneMatrices,
  13277. node: buffer( previousBoneMatrices, 'mat4', skeleton.bones.length )
  13278. };
  13279. _previousBoneMatricesData.set( skeleton, data );
  13280. }
  13281. return getSkinnedPosition( data.node, positionPrevious, bindMatrixNode, bindMatrixInverseNode, skinIndexNode, skinWeightNode );
  13282. }
  13283. /**
  13284. * TSL function representing the standard skeletal animation vertex shader setup.
  13285. * Transforms positionLocal, normalLocal, and tangentLocal in-place.
  13286. *
  13287. * @tsl
  13288. * @function
  13289. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  13290. */
  13291. const skinning = /*@__PURE__*/ Fn( ( [ skinnedMesh ], builder ) => {
  13292. const skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  13293. const skinWeightNode = attribute( 'skinWeight', 'vec4' );
  13294. const bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  13295. const bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  13296. const boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  13297. OnObjectUpdate( ( { object, frameId } ) => {
  13298. const skeleton = object.skeleton;
  13299. if ( _skeletonsUpdated.get( skeleton ) !== frameId ) {
  13300. _skeletonsUpdated.set( skeleton, frameId );
  13301. const skeletonData = _previousBoneMatricesData.get( skeleton );
  13302. if ( skeletonData !== undefined ) {
  13303. skeletonData.previousBoneMatrices.set( skeleton.boneMatrices );
  13304. }
  13305. skeleton.update();
  13306. }
  13307. } );
  13308. if ( builder.needsPreviousData() ) {
  13309. const previousSkinnedPosition = getPreviousSkinnedPosition( skinnedMesh, bindMatrixNode, bindMatrixInverseNode, skinIndexNode, skinWeightNode );
  13310. positionPrevious.assign( previousSkinnedPosition );
  13311. }
  13312. const skinPosition = getSkinnedPosition( boneMatricesNode, positionLocal, bindMatrixNode, bindMatrixInverseNode, skinIndexNode, skinWeightNode );
  13313. positionLocal.assign( skinPosition );
  13314. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  13315. const { skinNormal, skinTangent } = getSkinnedNormalAndTangent( boneMatricesNode, normalLocal, tangentLocal, bindMatrixNode, bindMatrixInverseNode, skinIndexNode, skinWeightNode );
  13316. normalLocal.assign( skinNormal );
  13317. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  13318. tangentLocal.assign( skinTangent );
  13319. }
  13320. }
  13321. }, 'void' );
  13322. /**
  13323. * TSL function that computes skeletal animation for custom compute passes.
  13324. *
  13325. * @tsl
  13326. * @function
  13327. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  13328. * @param {Node<vec3>} [toPosition=null] - The target position node to assign.
  13329. * @returns {Node<vec3>} The computed skinned position node.
  13330. */
  13331. const computeSkinning = /*@__PURE__*/ Fn( ( [ skinnedMesh, toPosition = null ], builder ) => {
  13332. const positionNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'position' ).array, 3 ), 'vec3' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  13333. const skinIndexNode = storage( new InstancedBufferAttribute( new Uint32Array( skinnedMesh.geometry.getAttribute( 'skinIndex' ).array ), 4 ), 'uvec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  13334. const skinWeightNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'skinWeight' ).array, 4 ), 'vec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  13335. const bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  13336. const bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  13337. const boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  13338. const skeleton = skinnedMesh.skeleton;
  13339. OnObjectUpdate( ( { frameId } ) => {
  13340. if ( _skeletonsUpdated.get( skeleton ) !== frameId ) {
  13341. _skeletonsUpdated.set( skeleton, frameId );
  13342. const state = _previousBoneMatricesData.get( skeleton );
  13343. if ( state !== undefined ) {
  13344. state.previousBoneMatrices.set( skeleton.boneMatrices );
  13345. }
  13346. skeleton.update();
  13347. }
  13348. } );
  13349. if ( builder.needsPreviousData() ) {
  13350. const previousSkinnedPosition = getPreviousSkinnedPosition( skinnedMesh, bindMatrixNode, bindMatrixInverseNode, skinIndexNode, skinWeightNode );
  13351. positionPrevious.assign( previousSkinnedPosition );
  13352. }
  13353. const skinPosition = getSkinnedPosition( boneMatricesNode, positionNode, bindMatrixNode, bindMatrixInverseNode, skinIndexNode, skinWeightNode );
  13354. if ( toPosition !== null ) {
  13355. toPosition.assign( skinPosition );
  13356. }
  13357. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  13358. const { skinNormal, skinTangent } = getSkinnedNormalAndTangent( boneMatricesNode, normalLocal, tangentLocal, bindMatrixNode, bindMatrixInverseNode, skinIndexNode, skinWeightNode );
  13359. normalLocal.assign( skinNormal );
  13360. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  13361. tangentLocal.assign( skinTangent );
  13362. }
  13363. }
  13364. return skinPosition;
  13365. } );
  13366. /**
  13367. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  13368. * ```js
  13369. * Loop( count, ( { i } ) => {
  13370. *
  13371. * } );
  13372. * ```
  13373. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  13374. * ```js
  13375. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  13376. *
  13377. * } );
  13378. *```
  13379. * Nested loops can be defined in a compacted form:
  13380. * ```js
  13381. * Loop( 10, 5, ( { i, j } ) => {
  13382. *
  13383. * } );
  13384. * ```
  13385. * Loops that should run backwards can be defined like so:
  13386. * ```js
  13387. * Loop( { start: 10 }, () => {} );
  13388. * ```
  13389. * It is possible to execute with boolean values, similar to the `while` syntax.
  13390. * ```js
  13391. * const value = float( 0 ).toVar();
  13392. *
  13393. * Loop( value.lessThan( 10 ), () => {
  13394. *
  13395. * value.addAssign( 1 );
  13396. *
  13397. * } );
  13398. * ```
  13399. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  13400. * @augments Node
  13401. */
  13402. class LoopNode extends Node {
  13403. static get type() {
  13404. return 'LoopNode';
  13405. }
  13406. /**
  13407. * Constructs a new loop node.
  13408. *
  13409. * @param {Array<any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  13410. */
  13411. constructor( params = [] ) {
  13412. super( 'void' );
  13413. this.params = params;
  13414. }
  13415. /**
  13416. * Returns a loop variable name based on an index. The pattern is
  13417. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  13418. *
  13419. * @param {number} index - The index.
  13420. * @return {string} The loop variable name.
  13421. */
  13422. getVarName( index ) {
  13423. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  13424. }
  13425. /**
  13426. * Returns properties about this node.
  13427. *
  13428. * @param {NodeBuilder} builder - The current node builder.
  13429. * @return {Object} The node properties.
  13430. */
  13431. getProperties( builder ) {
  13432. const properties = builder.getNodeProperties( this );
  13433. if ( properties.stackNode !== undefined ) return properties;
  13434. //
  13435. const inputs = {};
  13436. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  13437. const param = this.params[ i ];
  13438. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  13439. const type = ( param.isNode !== true && param.type ) || 'int';
  13440. inputs[ name ] = expression( name, type );
  13441. }
  13442. const stack = builder.addStack();
  13443. const fnCall = this.params[ this.params.length - 1 ]( inputs );
  13444. properties.returnsNode = fnCall.context( { nodeLoop: fnCall } );
  13445. properties.stackNode = stack;
  13446. const baseParam = this.params[ 0 ];
  13447. if ( baseParam.isNode !== true && typeof baseParam.update === 'function' ) {
  13448. const fnUpdateCall = Fn( this.params[ 0 ].update )( inputs );
  13449. properties.updateNode = fnUpdateCall.context( { nodeLoop: fnUpdateCall } );
  13450. }
  13451. builder.removeStack();
  13452. return properties;
  13453. }
  13454. setup( builder ) {
  13455. // setup properties
  13456. this.getProperties( builder );
  13457. if ( builder.fnCall ) {
  13458. const shaderNodeData = builder.getDataFromNode( builder.fnCall.shaderNode );
  13459. shaderNodeData.hasLoop = true;
  13460. }
  13461. }
  13462. generate( builder ) {
  13463. const properties = this.getProperties( builder );
  13464. const params = this.params;
  13465. const stackNode = properties.stackNode;
  13466. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  13467. const param = params[ i ];
  13468. let isWhile = false, start = null, end = null, name = null, type = null, condition = null, update = null;
  13469. if ( param.isNode ) {
  13470. if ( param.getNodeType( builder ) === 'bool' ) {
  13471. isWhile = true;
  13472. type = 'bool';
  13473. end = param.build( builder, type );
  13474. } else {
  13475. type = 'int';
  13476. name = this.getVarName( i );
  13477. start = '0';
  13478. end = param.build( builder, type );
  13479. condition = '<';
  13480. }
  13481. } else {
  13482. type = param.type || 'int';
  13483. name = param.name || this.getVarName( i );
  13484. start = param.start;
  13485. end = param.end;
  13486. condition = param.condition;
  13487. update = param.update;
  13488. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  13489. else if ( start && start.isNode ) start = start.build( builder, type );
  13490. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  13491. else if ( end && end.isNode ) end = end.build( builder, type );
  13492. if ( start !== undefined && end === undefined ) {
  13493. start = start + ' - 1';
  13494. end = '0';
  13495. condition = '>=';
  13496. } else if ( end !== undefined && start === undefined ) {
  13497. start = '0';
  13498. condition = '<';
  13499. }
  13500. if ( condition === undefined ) {
  13501. if ( Number( start ) > Number( end ) ) {
  13502. condition = '>=';
  13503. } else {
  13504. condition = '<';
  13505. }
  13506. }
  13507. }
  13508. let loopSnippet;
  13509. if ( isWhile ) {
  13510. loopSnippet = `while ( ${ end } )`;
  13511. } else {
  13512. const internalParam = { start, end};
  13513. //
  13514. const startSnippet = internalParam.start;
  13515. const endSnippet = internalParam.end;
  13516. let updateSnippet;
  13517. const deltaOperator = () => condition.includes( '<' ) ? '+=' : '-=';
  13518. if ( update !== undefined && update !== null ) {
  13519. switch ( typeof update ) {
  13520. case 'function':
  13521. const flow = builder.flowStagesNode( properties.updateNode, 'void' );
  13522. const snippet = flow.code.replace( /\t|;/g, '' );
  13523. updateSnippet = snippet;
  13524. break;
  13525. case 'number':
  13526. updateSnippet = name + ' ' + deltaOperator() + ' ' + builder.generateConst( type, update );
  13527. break;
  13528. case 'string':
  13529. updateSnippet = name + ' ' + update;
  13530. break;
  13531. default:
  13532. if ( update.isNode ) {
  13533. updateSnippet = name + ' ' + deltaOperator() + ' ' + update.build( builder );
  13534. } else {
  13535. error( 'TSL: \'Loop( { update: ... } )\' is not a function, string or number.', this.stackTrace );
  13536. updateSnippet = 'break /* invalid update */';
  13537. }
  13538. }
  13539. } else {
  13540. if ( type === 'int' || type === 'uint' ) {
  13541. update = condition.includes( '<' ) ? '++' : '--';
  13542. } else {
  13543. update = deltaOperator() + ' 1.';
  13544. }
  13545. updateSnippet = name + ' ' + update;
  13546. }
  13547. const declarationSnippet = builder.getVar( type, name ) + ' = ' + startSnippet;
  13548. const conditionalSnippet = name + ' ' + condition + ' ' + endSnippet;
  13549. loopSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  13550. }
  13551. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + loopSnippet + ' {\n\n' ).addFlowTab();
  13552. }
  13553. const stackSnippet = stackNode.build( builder, 'void' );
  13554. properties.returnsNode.build( builder, 'void' );
  13555. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  13556. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  13557. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  13558. }
  13559. builder.addFlowTab();
  13560. }
  13561. }
  13562. /**
  13563. * TSL function for creating a loop node.
  13564. *
  13565. * @tsl
  13566. * @function
  13567. * @param {...any} params - A list of parameters.
  13568. * @returns {LoopNode}
  13569. */
  13570. const Loop = ( ...params ) => new LoopNode( nodeArray( params, 'int' ) ).toStack();
  13571. /**
  13572. * TSL function for creating a `Continue()` expression.
  13573. *
  13574. * @tsl
  13575. * @function
  13576. * @returns {ExpressionNode}
  13577. */
  13578. const Continue = () => expression( 'continue' ).toStack();
  13579. /**
  13580. * TSL function for creating a `Break()` expression.
  13581. *
  13582. * @tsl
  13583. * @function
  13584. * @returns {ExpressionNode}
  13585. */
  13586. const Break = () => expression( 'break' ).toStack();
  13587. const _morphTextures = /*@__PURE__*/ new WeakMap();
  13588. const _morphVec4 = /*@__PURE__*/ new Vector4();
  13589. const _morphInfluencesData = /*@__PURE__*/ new WeakMap();
  13590. /**
  13591. * TSL function that retrieves and scales the morphed attribute (position or normal) texel value.
  13592. *
  13593. * @param {Object} params - The parameter object.
  13594. * @param {Node<texture>} params.bufferMap - The morph target data array texture.
  13595. * @param {Node<float>} params.influence - The target's animation influence weight.
  13596. * @param {number} params.stride - The vertex data stride (e.g. 1 or 2).
  13597. * @param {Node<int>} params.width - The texture width limit.
  13598. * @param {Node<int>} params.depth - The target layer index (morph target index).
  13599. * @param {Node<int>} params.offset - The texture offset (e.g. 0 for position, 1 for normal).
  13600. * @returns {Node<vec3>} The scaled morph target translation value.
  13601. */
  13602. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  13603. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  13604. const y = texelIndex.div( width );
  13605. const x = texelIndex.sub( y.mul( width ) );
  13606. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth ).xyz;
  13607. return bufferAttrib.mul( influence );
  13608. } );
  13609. /**
  13610. * Resolves or creates a compiled DataArrayTexture containing encoded vertex morph targets data for WebGL2/WebGPU.
  13611. *
  13612. * @param {BufferGeometry} geometry - The geometry to parse.
  13613. * @returns {Object} The resolved morph targets texture data mapping entry.
  13614. */
  13615. function getEntry( geometry ) {
  13616. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  13617. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  13618. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  13619. // instead of using attributes, the WebGL 2 code path encodes morph targets
  13620. // into an array of data textures. Each layer represents a single morph target.
  13621. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  13622. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  13623. let entry = _morphTextures.get( geometry );
  13624. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  13625. if ( entry !== undefined ) entry.texture.dispose();
  13626. const morphTargets = geometry.morphAttributes.position || [];
  13627. const morphNormals = geometry.morphAttributes.normal || [];
  13628. const morphColors = geometry.morphAttributes.color || [];
  13629. let vertexDataCount = 0;
  13630. if ( hasMorphPosition === true ) vertexDataCount = 1;
  13631. if ( hasMorphNormals === true ) vertexDataCount = 2;
  13632. if ( hasMorphColors === true ) vertexDataCount = 3;
  13633. let width = geometry.attributes.position.count * vertexDataCount;
  13634. let height = 1;
  13635. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  13636. if ( width > maxTextureSize ) {
  13637. height = Math.ceil( width / maxTextureSize );
  13638. width = maxTextureSize;
  13639. }
  13640. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  13641. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  13642. bufferTexture.type = FloatType;
  13643. bufferTexture.needsUpdate = true;
  13644. // fill buffer
  13645. const vertexDataStride = vertexDataCount * 4;
  13646. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  13647. const morphTarget = morphTargets[ i ];
  13648. const morphNormal = morphNormals[ i ];
  13649. const morphColor = morphColors[ i ];
  13650. const offset = width * height * 4 * i;
  13651. for ( let j = 0; j < morphTarget.count; j ++ ) {
  13652. const stride = j * vertexDataStride;
  13653. if ( hasMorphPosition === true ) {
  13654. _morphVec4.fromBufferAttribute( morphTarget, j );
  13655. buffer[ offset + stride + 0 ] = _morphVec4.x;
  13656. buffer[ offset + stride + 1 ] = _morphVec4.y;
  13657. buffer[ offset + stride + 2 ] = _morphVec4.z;
  13658. buffer[ offset + stride + 3 ] = 0;
  13659. }
  13660. if ( hasMorphNormals === true ) {
  13661. _morphVec4.fromBufferAttribute( morphNormal, j );
  13662. buffer[ offset + stride + 4 ] = _morphVec4.x;
  13663. buffer[ offset + stride + 5 ] = _morphVec4.y;
  13664. buffer[ offset + stride + 6 ] = _morphVec4.z;
  13665. buffer[ offset + stride + 7 ] = 0;
  13666. }
  13667. if ( hasMorphColors === true ) {
  13668. _morphVec4.fromBufferAttribute( morphColor, j );
  13669. buffer[ offset + stride + 8 ] = _morphVec4.x;
  13670. buffer[ offset + stride + 9 ] = _morphVec4.y;
  13671. buffer[ offset + stride + 10 ] = _morphVec4.z;
  13672. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  13673. }
  13674. }
  13675. }
  13676. entry = {
  13677. count: morphTargetsCount,
  13678. texture: bufferTexture,
  13679. stride: vertexDataCount,
  13680. size: new Vector2( width, height )
  13681. };
  13682. _morphTextures.set( geometry, entry );
  13683. function disposeTexture() {
  13684. bufferTexture.dispose();
  13685. _morphTextures.delete( geometry );
  13686. geometry.removeEventListener( 'dispose', disposeTexture );
  13687. }
  13688. geometry.addEventListener( 'dispose', disposeTexture );
  13689. }
  13690. return entry;
  13691. }
  13692. /**
  13693. * TSL function representing the vertex shader morph targets blend setup.
  13694. * Dynamically computes morph targets weights and updates positionLocal and normalLocal in-place.
  13695. *
  13696. * @tsl
  13697. * @function
  13698. * @param {Mesh} mesh - The mesh.
  13699. */
  13700. const morphReference = /*@__PURE__*/ Fn( ( [ mesh ] ) => {
  13701. const { geometry } = mesh;
  13702. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  13703. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  13704. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  13705. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  13706. if ( morphTargetsCount === 0 ) return;
  13707. // Init
  13708. let morphInfluenceData = _morphInfluencesData.get( mesh );
  13709. if ( morphInfluenceData === undefined || morphInfluenceData.count !== morphTargetsCount ) {
  13710. morphInfluenceData = {
  13711. base: uniform( 1 ),
  13712. influences: mesh.morphTargetInfluences ? uniformArray( mesh.morphTargetInfluences, 'float' ) : null,
  13713. count: morphTargetsCount
  13714. };
  13715. _morphInfluencesData.set( mesh, morphInfluenceData );
  13716. }
  13717. const { base, influences } = morphInfluenceData;
  13718. // Shader
  13719. const { texture: bufferMap, stride, size } = getEntry( geometry );
  13720. if ( hasMorphPosition === true ) positionLocal.mulAssign( base );
  13721. if ( hasMorphNormals === true ) normalLocal.mulAssign( base );
  13722. const width = int( size.width );
  13723. Loop( morphTargetsCount, ( { i } ) => {
  13724. const influence = float( 0 ).toVar();
  13725. if ( mesh.count > 1 && ( mesh.morphTexture !== null && mesh.morphTexture !== undefined ) ) {
  13726. influence.assign( textureLoad( mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  13727. } else {
  13728. influence.assign( influences.element( i ).toVar() );
  13729. }
  13730. If( influence.notEqual( 0 ), () => {
  13731. if ( hasMorphPosition === true ) {
  13732. positionLocal.addAssign( getMorph( {
  13733. bufferMap,
  13734. influence,
  13735. stride,
  13736. width,
  13737. depth: i,
  13738. offset: int( 0 )
  13739. } ) );
  13740. }
  13741. if ( hasMorphNormals === true ) {
  13742. normalLocal.addAssign( getMorph( {
  13743. bufferMap,
  13744. influence,
  13745. stride,
  13746. width,
  13747. depth: i,
  13748. offset: int( 1 )
  13749. } ) );
  13750. }
  13751. } );
  13752. } );
  13753. // Update
  13754. OnObjectUpdate( ( { object } ) => {
  13755. const { base, influences } = morphInfluenceData;
  13756. if ( object.geometry.morphTargetsRelative ) {
  13757. base.value = 1;
  13758. } else {
  13759. base.value = 1 - object.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  13760. }
  13761. if ( influences ) {
  13762. influences.array = object.morphTargetInfluences;
  13763. influences.update();
  13764. }
  13765. } );
  13766. }, 'void' );
  13767. /**
  13768. * Base class for lighting nodes.
  13769. *
  13770. * @augments Node
  13771. */
  13772. class LightingNode extends Node {
  13773. static get type() {
  13774. return 'LightingNode';
  13775. }
  13776. /**
  13777. * Constructs a new lighting node.
  13778. */
  13779. constructor() {
  13780. super( 'vec3' );
  13781. /**
  13782. * This flag can be used for type testing.
  13783. *
  13784. * @type {boolean}
  13785. * @readonly
  13786. * @default true
  13787. */
  13788. this.isLightingNode = true;
  13789. }
  13790. }
  13791. /**
  13792. * A generic class that can be used by nodes which contribute
  13793. * ambient occlusion to the scene. E.g. an ambient occlusion map
  13794. * node can be used as input for this module. Used in {@link NodeMaterial}.
  13795. *
  13796. * @augments LightingNode
  13797. */
  13798. class AONode extends LightingNode {
  13799. static get type() {
  13800. return 'AONode';
  13801. }
  13802. /**
  13803. * Constructs a new AO node.
  13804. *
  13805. * @param {?Node<float>} [aoNode=null] - The ambient occlusion node.
  13806. */
  13807. constructor( aoNode = null ) {
  13808. super();
  13809. /**
  13810. * The ambient occlusion node.
  13811. *
  13812. * @type {?Node<float>}
  13813. * @default null
  13814. */
  13815. this.aoNode = aoNode;
  13816. }
  13817. setup( builder ) {
  13818. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  13819. }
  13820. }
  13821. /**
  13822. * `LightingContextNode` represents an extension of the {@link ContextNode} module
  13823. * by adding lighting specific context data. It represents the runtime context of
  13824. * {@link LightsNode}.
  13825. *
  13826. * @augments ContextNode
  13827. */
  13828. class LightingContextNode extends ContextNode {
  13829. static get type() {
  13830. return 'LightingContextNode';
  13831. }
  13832. /**
  13833. * Constructs a new lighting context node.
  13834. *
  13835. * @param {LightsNode} lightsNode - The lights node.
  13836. * @param {?LightingModel} [lightingModel=null] - The current lighting model.
  13837. * @param {?Array<LightingNode>} materialLightings - The material lightings nodes.
  13838. * @param {?Node<vec3>} [backdropNode=null] - A backdrop node.
  13839. * @param {?Node<float>} [backdropAlphaNode=null] - A backdrop alpha node.
  13840. */
  13841. constructor( lightsNode, lightingModel = null, materialLightings = [], backdropNode = null, backdropAlphaNode = null ) {
  13842. super( lightsNode );
  13843. /**
  13844. * The current lighting model.
  13845. *
  13846. * @type {?LightingModel}
  13847. * @default null
  13848. */
  13849. this.lightingModel = lightingModel;
  13850. /**
  13851. * @type {?Array<LightingNode>}
  13852. * @default []
  13853. */
  13854. this.materialLightings = materialLightings;
  13855. /**
  13856. * A backdrop node.
  13857. *
  13858. * @type {?Node<vec3>}
  13859. * @default null
  13860. */
  13861. this.backdropNode = backdropNode;
  13862. /**
  13863. * A backdrop alpha node.
  13864. *
  13865. * @type {?Node<float>}
  13866. * @default null
  13867. */
  13868. this.backdropAlphaNode = backdropAlphaNode;
  13869. this._value = null;
  13870. }
  13871. /**
  13872. * Returns a lighting context object.
  13873. *
  13874. * @return {{
  13875. * radiance: Node<vec3>,
  13876. * irradiance: Node<vec3>,
  13877. * iblIrradiance: Node<vec3>,
  13878. * ambientOcclusion: Node<float>,
  13879. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  13880. * backdrop: Node<vec3>,
  13881. * backdropAlpha: Node<float>
  13882. * }} The lighting context object.
  13883. */
  13884. getContext() {
  13885. const { materialLightings, backdropNode, backdropAlphaNode } = this;
  13886. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  13887. directSpecular = vec3().toVar( 'directSpecular' ),
  13888. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  13889. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  13890. const reflectedLight = {
  13891. directDiffuse,
  13892. directSpecular,
  13893. indirectDiffuse,
  13894. indirectSpecular
  13895. };
  13896. const context = {
  13897. radiance: vec3().toVar( 'radiance' ),
  13898. irradiance: vec3().toVar( 'irradiance' ),
  13899. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  13900. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  13901. reflectedLight,
  13902. materialLightings,
  13903. backdrop: backdropNode,
  13904. backdropAlpha: backdropAlphaNode
  13905. };
  13906. return context;
  13907. }
  13908. setup( builder ) {
  13909. this.value = this._value || ( this._value = this.getContext() );
  13910. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  13911. return super.setup( builder );
  13912. }
  13913. }
  13914. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  13915. /**
  13916. * A generic class that can be used by nodes which contribute
  13917. * irradiance to the scene. E.g. a light map node can be used
  13918. * as input for this module. Used in {@link NodeMaterial}.
  13919. *
  13920. * @augments LightingNode
  13921. */
  13922. class IrradianceNode extends LightingNode {
  13923. static get type() {
  13924. return 'IrradianceNode';
  13925. }
  13926. /**
  13927. * Constructs a new irradiance node.
  13928. *
  13929. * @param {Node<vec3>} node - A node contributing irradiance.
  13930. */
  13931. constructor( node ) {
  13932. super();
  13933. /**
  13934. * A node contributing irradiance.
  13935. *
  13936. * @type {Node<vec3>}
  13937. */
  13938. this.node = node;
  13939. }
  13940. setup( builder ) {
  13941. builder.context.irradiance.addAssign( this.node );
  13942. }
  13943. }
  13944. const _size$5 = /*@__PURE__*/ new Vector2();
  13945. /**
  13946. * A special type of texture node which represents the data of the current viewport
  13947. * as a texture. The module extracts data from the current bound framebuffer with
  13948. * a copy operation so no extra render pass is required to produce the texture data
  13949. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  13950. * variety of effects like refractive or transmissive materials.
  13951. *
  13952. * @augments TextureNode
  13953. */
  13954. class ViewportTextureNode extends TextureNode {
  13955. static get type() {
  13956. return 'ViewportTextureNode';
  13957. }
  13958. /**
  13959. * Constructs a new viewport texture node.
  13960. *
  13961. * @param {Node} [uvNode=screenUV] - The uv node.
  13962. * @param {?Node} [levelNode=null] - The level node.
  13963. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13964. */
  13965. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  13966. let defaultFramebuffer = null;
  13967. if ( framebufferTexture === null ) {
  13968. defaultFramebuffer = new FramebufferTexture();
  13969. defaultFramebuffer.minFilter = LinearMipmapLinearFilter;
  13970. framebufferTexture = defaultFramebuffer;
  13971. } else {
  13972. defaultFramebuffer = framebufferTexture;
  13973. }
  13974. super( framebufferTexture, uvNode, levelNode );
  13975. /**
  13976. * Whether to generate mipmaps or not.
  13977. *
  13978. * @type {boolean}
  13979. * @default false
  13980. */
  13981. this.generateMipmaps = false;
  13982. /**
  13983. * The reference framebuffer texture. This is used to store the framebuffer texture
  13984. * for the current render target. If the render target changes, a new framebuffer texture
  13985. * is created automatically.
  13986. *
  13987. * @type {FramebufferTexture}
  13988. * @default null
  13989. */
  13990. this.defaultFramebuffer = defaultFramebuffer;
  13991. /**
  13992. * This flag can be used for type testing.
  13993. *
  13994. * @type {boolean}
  13995. * @readonly
  13996. * @default true
  13997. */
  13998. this.isOutputTextureNode = true;
  13999. /**
  14000. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node should extract
  14001. * the current contents of the bound framebuffer for each render call.
  14002. *
  14003. * @type {string}
  14004. * @default 'render'
  14005. */
  14006. this.updateBeforeType = NodeUpdateType.RENDER;
  14007. /**
  14008. * The framebuffer texture for the current renderer context.
  14009. *
  14010. * @type {WeakMap<RenderTarget, FramebufferTexture>}
  14011. * @private
  14012. */
  14013. this._cacheTextures = new WeakMap();
  14014. }
  14015. /**
  14016. * This methods returns a texture for the given render target or canvas target reference.
  14017. *
  14018. * To avoid rendering errors, `ViewportTextureNode` must use unique framebuffer textures
  14019. * for different render contexts.
  14020. *
  14021. * @param {?(RenderTarget|CanvasTarget)} [reference=null] - The render target or canvas target reference.
  14022. * @return {Texture} The framebuffer texture.
  14023. */
  14024. getTextureForReference( reference = null ) {
  14025. let defaultFramebuffer;
  14026. let cacheTextures;
  14027. if ( this.referenceNode ) {
  14028. defaultFramebuffer = this.referenceNode.defaultFramebuffer;
  14029. cacheTextures = this.referenceNode._cacheTextures;
  14030. } else {
  14031. defaultFramebuffer = this.defaultFramebuffer;
  14032. cacheTextures = this._cacheTextures;
  14033. }
  14034. if ( reference === null ) {
  14035. return defaultFramebuffer;
  14036. }
  14037. if ( cacheTextures.has( reference ) === false ) {
  14038. const framebufferTexture = defaultFramebuffer.clone();
  14039. cacheTextures.set( reference, framebufferTexture );
  14040. }
  14041. return cacheTextures.get( reference );
  14042. }
  14043. updateReference( frame ) {
  14044. const renderer = frame.renderer;
  14045. const renderTarget = renderer.getRenderTarget();
  14046. const canvasTarget = renderer.getCanvasTarget();
  14047. const reference = renderTarget ? renderTarget : canvasTarget;
  14048. this.value = this.getTextureForReference( reference );
  14049. return this.value;
  14050. }
  14051. updateBefore( frame ) {
  14052. const renderer = frame.renderer;
  14053. const renderTarget = renderer.getRenderTarget();
  14054. const canvasTarget = renderer.getCanvasTarget();
  14055. const reference = renderTarget ? renderTarget : canvasTarget;
  14056. if ( reference === null ) {
  14057. renderer.getDrawingBufferSize( _size$5 );
  14058. } else if ( reference.getDrawingBufferSize ) {
  14059. reference.getDrawingBufferSize( _size$5 );
  14060. } else {
  14061. _size$5.set( reference.width, reference.height );
  14062. }
  14063. //
  14064. const framebufferTexture = this.getTextureForReference( reference );
  14065. if ( framebufferTexture.image.width !== _size$5.width || framebufferTexture.image.height !== _size$5.height ) {
  14066. framebufferTexture.image.width = _size$5.width;
  14067. framebufferTexture.image.height = _size$5.height;
  14068. framebufferTexture.needsUpdate = true;
  14069. }
  14070. //
  14071. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  14072. framebufferTexture.generateMipmaps = this.generateMipmaps;
  14073. renderer.copyFramebufferToTexture( framebufferTexture );
  14074. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  14075. }
  14076. clone() {
  14077. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  14078. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  14079. return viewportTextureNode;
  14080. }
  14081. }
  14082. /**
  14083. * TSL function for creating a viewport texture node.
  14084. *
  14085. * @tsl
  14086. * @function
  14087. * @param {?Node} [uvNode=screenUV] - The uv node.
  14088. * @param {?Node} [levelNode=null] - The level node.
  14089. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  14090. * @returns {ViewportTextureNode}
  14091. */
  14092. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode ).setParameterLength( 0, 3 );
  14093. /**
  14094. * TSL function for creating a viewport texture node with enabled mipmap generation.
  14095. *
  14096. * @tsl
  14097. * @function
  14098. * @param {?Node} [uvNode=screenUV] - The uv node.
  14099. * @param {?Node} [levelNode=null] - The level node.
  14100. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  14101. * @returns {ViewportTextureNode}
  14102. */
  14103. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } ).setParameterLength( 0, 3 );
  14104. // Singleton instances for common usage
  14105. const _singletonOpaqueViewportTextureNode = /*@__PURE__*/ viewportMipTexture();
  14106. /**
  14107. * TSL function for creating a viewport texture node with enabled mipmap generation.
  14108. * The texture should only contain the opaque rendering objects.
  14109. *
  14110. * This should be used just in transparent or transmissive materials.
  14111. *
  14112. * @tsl
  14113. * @function
  14114. * @param {?Node} [uv=screenUV] - The uv node.
  14115. * @param {?Node} [level=null] - The level node.
  14116. * @returns {ViewportTextureNode}
  14117. */
  14118. const viewportOpaqueMipTexture = ( uv = screenUV, level = null ) => _singletonOpaqueViewportTextureNode.sample( uv, level ); // TODO: Use once() when sample() supports it
  14119. let _sharedDepthbuffer = null;
  14120. /**
  14121. * Represents the depth of the current viewport as a texture. This module
  14122. * can be used in combination with viewport texture to achieve effects
  14123. * that require depth evaluation.
  14124. *
  14125. * @augments ViewportTextureNode
  14126. */
  14127. class ViewportDepthTextureNode extends ViewportTextureNode {
  14128. static get type() {
  14129. return 'ViewportDepthTextureNode';
  14130. }
  14131. /**
  14132. * Constructs a new viewport depth texture node.
  14133. *
  14134. * @param {Node} [uvNode=screenUV] - The uv node.
  14135. * @param {?Node} [levelNode=null] - The level node.
  14136. * @param {?DepthTexture} [depthTexture=null] - A depth texture. If not provided, uses a shared depth texture.
  14137. */
  14138. constructor( uvNode = screenUV, levelNode = null, depthTexture = null ) {
  14139. if ( depthTexture === null ) {
  14140. if ( _sharedDepthbuffer === null ) {
  14141. _sharedDepthbuffer = new DepthTexture();
  14142. }
  14143. depthTexture = _sharedDepthbuffer;
  14144. }
  14145. super( uvNode, levelNode, depthTexture );
  14146. }
  14147. }
  14148. /**
  14149. * TSL function for a viewport depth texture node.
  14150. *
  14151. * @tsl
  14152. * @function
  14153. * @param {?Node} [uvNode=screenUV] - The uv node.
  14154. * @param {?Node} [levelNode=null] - The level node.
  14155. * @param {?DepthTexture} [depthTexture=null] - A depth texture. If not provided, a depth texture is created automatically.
  14156. * @returns {ViewportDepthTextureNode}
  14157. */
  14158. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode ).setParameterLength( 0, 3 );
  14159. /**
  14160. * This node offers a collection of features in context of the depth logic in the fragment shader.
  14161. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  14162. * fragment or for depth evaluation purposes.
  14163. *
  14164. * @augments Node
  14165. */
  14166. class ViewportDepthNode extends Node {
  14167. static get type() {
  14168. return 'ViewportDepthNode';
  14169. }
  14170. /**
  14171. * Constructs a new viewport depth node.
  14172. *
  14173. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  14174. * @param {?Node} [valueNode=null] - The value node.
  14175. */
  14176. constructor( scope, valueNode = null ) {
  14177. super( 'float' );
  14178. /**
  14179. * The node behaves differently depending on which scope is selected.
  14180. *
  14181. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  14182. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  14183. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  14184. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  14185. *
  14186. * @type {('depth'|'depthBase'|'linearDepth')}
  14187. */
  14188. this.scope = scope;
  14189. /**
  14190. * Can be used to define a custom depth value.
  14191. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  14192. *
  14193. * @type {?Node}
  14194. * @default null
  14195. */
  14196. this.valueNode = valueNode;
  14197. /**
  14198. * This flag can be used for type testing.
  14199. *
  14200. * @type {boolean}
  14201. * @readonly
  14202. * @default true
  14203. */
  14204. this.isViewportDepthNode = true;
  14205. }
  14206. generate( builder ) {
  14207. const { scope } = this;
  14208. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  14209. return builder.getFragDepth();
  14210. }
  14211. return super.generate( builder );
  14212. }
  14213. setup( { camera } ) {
  14214. const { scope } = this;
  14215. const value = this.valueNode;
  14216. let node = null;
  14217. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  14218. if ( value !== null ) {
  14219. node = depthBase().assign( value );
  14220. }
  14221. } else if ( scope === ViewportDepthNode.DEPTH ) {
  14222. if ( camera.isPerspectiveCamera ) {
  14223. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  14224. } else {
  14225. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  14226. }
  14227. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  14228. if ( value !== null ) {
  14229. if ( camera.isPerspectiveCamera ) {
  14230. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  14231. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  14232. } else {
  14233. node = value;
  14234. }
  14235. } else {
  14236. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  14237. }
  14238. }
  14239. return node;
  14240. }
  14241. }
  14242. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  14243. ViewportDepthNode.DEPTH = 'depth';
  14244. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  14245. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  14246. /**
  14247. * TSL function for converting a viewZ value to an orthographic depth value.
  14248. *
  14249. * @tsl
  14250. * @function
  14251. * @param {Node<float>} viewZ - The viewZ node.
  14252. * @param {Node<float>} near - The camera's near value.
  14253. * @param {Node<float>} far - The camera's far value.
  14254. * @returns {Node<float>}
  14255. */
  14256. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  14257. /**
  14258. * TSL function for converting a viewZ value to a reversed orthographic depth value.
  14259. *
  14260. * @tsl
  14261. * @function
  14262. * @param {Node<float>} viewZ - The viewZ node.
  14263. * @param {Node<float>} near - The camera's near value.
  14264. * @param {Node<float>} far - The camera's far value.
  14265. * @returns {Node<float>}
  14266. */
  14267. const viewZToReversedOrthographicDepth = ( viewZ, near, far ) => viewZ.add( far ).div( far.sub( near ) );
  14268. /**
  14269. * TSL function for converting an orthographic depth value to a viewZ value.
  14270. *
  14271. * @tsl
  14272. * @function
  14273. * @param {Node<float>} depth - The orthographic depth.
  14274. * @param {Node<float>} near - The camera's near value.
  14275. * @param {Node<float>} far - The camera's far value.
  14276. * @returns {Node<float>}
  14277. */
  14278. const orthographicDepthToViewZ = /*@__PURE__*/ Fn( ( [ depth, near, far ], builder ) => {
  14279. if ( builder.renderer.reversedDepthBuffer === true ) {
  14280. return far.sub( near ).mul( depth ).sub( far );
  14281. } else {
  14282. return near.sub( far ).mul( depth ).sub( near );
  14283. }
  14284. } );
  14285. /**
  14286. * TSL function for converting a viewZ value to a perspective depth value.
  14287. *
  14288. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  14289. *
  14290. * @tsl
  14291. * @function
  14292. * @param {Node<float>} viewZ - The viewZ node.
  14293. * @param {Node<float>} near - The camera's near value.
  14294. * @param {Node<float>} far - The camera's far value.
  14295. * @returns {Node<float>}
  14296. */
  14297. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  14298. /**
  14299. * TSL function for converting a viewZ value to a reversed perspective depth value.
  14300. *
  14301. * @tsl
  14302. * @function
  14303. * @param {Node<float>} viewZ - The viewZ node.
  14304. * @param {Node<float>} near - The camera's near value.
  14305. * @param {Node<float>} far - The camera's far value.
  14306. * @returns {Node<float>}
  14307. */
  14308. const viewZToReversedPerspectiveDepth = ( viewZ, near, far ) => near.mul( viewZ.add( far ) ).div( viewZ.mul( near.sub( far ) ) );
  14309. /**
  14310. * TSL function for converting a perspective depth value to a viewZ value.
  14311. *
  14312. * @tsl
  14313. * @function
  14314. * @param {Node<float>} depth - The perspective depth.
  14315. * @param {Node<float>} near - The camera's near value.
  14316. * @param {Node<float>} far - The camera's far value.
  14317. * @returns {Node<float>}
  14318. */
  14319. const perspectiveDepthToViewZ = /*@__PURE__*/ Fn( ( [ depth, near, far ], builder ) => {
  14320. if ( builder.renderer.reversedDepthBuffer === true ) {
  14321. return near.mul( far ).div( near.sub( far ).mul( depth ).sub( near ) );
  14322. } else {
  14323. return near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  14324. }
  14325. } );
  14326. /**
  14327. * TSL function for converting a viewZ value to a logarithmic depth value.
  14328. *
  14329. * @tsl
  14330. * @function
  14331. * @param {Node<float>} viewZ - The viewZ node.
  14332. * @param {Node<float>} near - The camera's near value.
  14333. * @param {Node<float>} far - The camera's far value.
  14334. * @returns {Node<float>}
  14335. */
  14336. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  14337. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  14338. // The final logarithmic depth formula used here is adapted from one described in an
  14339. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  14340. // which was an improvement upon an earlier formula one described in an
  14341. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  14342. // Ulrich's formula is the following:
  14343. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  14344. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  14345. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  14346. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  14347. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  14348. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  14349. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  14350. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  14351. // be used, and ultimately Ulrich's "near plane" version was chosen.
  14352. // Outerra eventually made another improvement to their original "C-constant" variant,
  14353. // but it still does not incorporate the camera near plane (for this version,
  14354. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  14355. // Here we make 4 changes to Ulrich's formula:
  14356. // 1. Clamp the camera near plane so we don't divide by 0.
  14357. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  14358. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  14359. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  14360. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  14361. // so we do the same here, hence the 'viewZ.negate()' call.
  14362. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  14363. near = near.max( 1e-6 ).toVar();
  14364. const numerator = log2( viewZ.negate().div( near ) );
  14365. const denominator = log2( far.div( near ) );
  14366. return numerator.div( denominator );
  14367. };
  14368. /**
  14369. * TSL function for converting a logarithmic depth value to a viewZ value.
  14370. *
  14371. * @tsl
  14372. * @function
  14373. * @param {Node<float>} depth - The logarithmic depth.
  14374. * @param {Node<float>} near - The camera's near value.
  14375. * @param {Node<float>} far - The camera's far value.
  14376. * @returns {Node<float>}
  14377. */
  14378. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  14379. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  14380. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  14381. // a negative viewZ).
  14382. const exponent = depth.mul( log( far.div( near ) ) );
  14383. return float( Math.E ).pow( exponent ).mul( near ).negate();
  14384. };
  14385. /**
  14386. * TSL function for defining a value for the current fragment's depth.
  14387. *
  14388. * @tsl
  14389. * @function
  14390. * @param {Node<float>} value - The depth value to set.
  14391. * @returns {ViewportDepthNode<float>}
  14392. */
  14393. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  14394. /**
  14395. * TSL object that represents the depth value for the current fragment.
  14396. *
  14397. * @tsl
  14398. * @type {ViewportDepthNode}
  14399. */
  14400. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  14401. /**
  14402. * TSL function for converting a perspective depth value to linear depth.
  14403. *
  14404. * @tsl
  14405. * @function
  14406. * @param {?Node<float>} [value=null] - The perspective depth. If `null` is provided, the current fragment's depth is used.
  14407. * @returns {ViewportDepthNode<float>}
  14408. */
  14409. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH ).setParameterLength( 0, 1 );
  14410. /**
  14411. * TSL object that represents the linear (orthographic) depth value of the current fragment
  14412. *
  14413. * @tsl
  14414. * @type {ViewportDepthNode}
  14415. */
  14416. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  14417. depth.assign = ( value ) => depthBase( value );
  14418. /**
  14419. * This node is used in {@link NodeMaterial} to setup the clipping
  14420. * which can happen hardware-accelerated (if supported) and optionally
  14421. * use alpha-to-coverage for anti-aliasing clipped edges.
  14422. *
  14423. * @augments Node
  14424. */
  14425. class ClippingNode extends Node {
  14426. static get type() {
  14427. return 'ClippingNode';
  14428. }
  14429. /**
  14430. * Constructs a new clipping node.
  14431. *
  14432. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  14433. * the selected scope influences the behavior of the node and what type of code is generated.
  14434. */
  14435. constructor( scope = ClippingNode.DEFAULT ) {
  14436. super();
  14437. /**
  14438. * The node's scope. Similar to other nodes, the selected scope influences
  14439. * the behavior of the node and what type of code is generated.
  14440. *
  14441. * @type {('default'|'hardware'|'alphaToCoverage')}
  14442. */
  14443. this.scope = scope;
  14444. }
  14445. /**
  14446. * Setups the node depending on the selected scope.
  14447. *
  14448. * @param {NodeBuilder} builder - The current node builder.
  14449. * @return {Node} The result node.
  14450. */
  14451. setup( builder ) {
  14452. super.setup( builder );
  14453. const clippingContext = builder.clippingContext;
  14454. const { intersectionPlanes, unionPlanes } = clippingContext;
  14455. this.hardwareClipping = builder.hardwareClipping;
  14456. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  14457. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  14458. } else if ( this.scope === ClippingNode.HARDWARE ) {
  14459. return this.setupHardwareClipping( unionPlanes, builder );
  14460. } else {
  14461. return this.setupDefault( intersectionPlanes, unionPlanes );
  14462. }
  14463. }
  14464. /**
  14465. * Setups alpha to coverage.
  14466. *
  14467. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  14468. * @param {Array<Vector4>} unionPlanes - The union planes.
  14469. * @return {Node} The result node.
  14470. */
  14471. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  14472. return Fn( () => {
  14473. const distanceToPlane = float().toVar( 'distanceToPlane' );
  14474. const distanceGradient = float().toVar( 'distanceToGradient' );
  14475. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  14476. const numUnionPlanes = unionPlanes.length;
  14477. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  14478. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  14479. Loop( numUnionPlanes, ( { i } ) => {
  14480. const plane = clippingPlanes.element( i );
  14481. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  14482. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  14483. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  14484. } );
  14485. }
  14486. const numIntersectionPlanes = intersectionPlanes.length;
  14487. if ( numIntersectionPlanes > 0 ) {
  14488. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  14489. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  14490. Loop( numIntersectionPlanes, ( { i } ) => {
  14491. const plane = clippingPlanes.element( i );
  14492. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  14493. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  14494. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  14495. } );
  14496. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  14497. }
  14498. diffuseColor.a.mulAssign( clipOpacity );
  14499. diffuseColor.a.equal( 0.0 ).discard();
  14500. } )();
  14501. }
  14502. /**
  14503. * Setups the default clipping.
  14504. *
  14505. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  14506. * @param {Array<Vector4>} unionPlanes - The union planes.
  14507. * @return {Node} The result node.
  14508. */
  14509. setupDefault( intersectionPlanes, unionPlanes ) {
  14510. return Fn( () => {
  14511. const numUnionPlanes = unionPlanes.length;
  14512. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  14513. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  14514. Loop( numUnionPlanes, ( { i } ) => {
  14515. const plane = clippingPlanes.element( i );
  14516. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  14517. } );
  14518. }
  14519. const numIntersectionPlanes = intersectionPlanes.length;
  14520. if ( numIntersectionPlanes > 0 ) {
  14521. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  14522. const clipped = bool( true ).toVar( 'clipped' );
  14523. Loop( numIntersectionPlanes, ( { i } ) => {
  14524. const plane = clippingPlanes.element( i );
  14525. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  14526. } );
  14527. clipped.discard();
  14528. }
  14529. } )();
  14530. }
  14531. /**
  14532. * Setups hardware clipping.
  14533. *
  14534. * @param {Array<Vector4>} unionPlanes - The union planes.
  14535. * @param {NodeBuilder} builder - The current node builder.
  14536. * @return {Node} The result node.
  14537. */
  14538. setupHardwareClipping( unionPlanes, builder ) {
  14539. const numUnionPlanes = unionPlanes.length;
  14540. builder.enableHardwareClipping( numUnionPlanes );
  14541. return Fn( () => {
  14542. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  14543. const hw_clip_distances = builtin( builder.getClipDistance() );
  14544. Loop( numUnionPlanes, ( { i } ) => {
  14545. const plane = clippingPlanes.element( i );
  14546. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  14547. hw_clip_distances.element( i ).assign( distance );
  14548. } );
  14549. } )();
  14550. }
  14551. }
  14552. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  14553. ClippingNode.DEFAULT = 'default';
  14554. ClippingNode.HARDWARE = 'hardware';
  14555. /**
  14556. * TSL function for setting up the default clipping logic.
  14557. *
  14558. * @tsl
  14559. * @function
  14560. * @returns {ClippingNode}
  14561. */
  14562. const clipping = () => new ClippingNode();
  14563. /**
  14564. * TSL function for setting up alpha to coverage.
  14565. *
  14566. * @tsl
  14567. * @function
  14568. * @returns {ClippingNode}
  14569. */
  14570. const clippingAlpha = () => new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE );
  14571. /**
  14572. * TSL function for setting up hardware-based clipping.
  14573. *
  14574. * @tsl
  14575. * @function
  14576. * @returns {ClippingNode}
  14577. */
  14578. const hardwareClipping = () => new ClippingNode( ClippingNode.HARDWARE );
  14579. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  14580. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  14581. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  14582. 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 ) ) ) ) ) );
  14583. } );
  14584. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  14585. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  14586. } );
  14587. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  14588. // Find the discretized derivatives of our coordinates
  14589. const maxDeriv = max$1(
  14590. length( dFdx( position.xyz ) ),
  14591. length( dFdy( position.xyz ) )
  14592. );
  14593. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  14594. // Find two nearest log-discretized noise scales
  14595. const pixScales = vec2(
  14596. exp2( floor( log2( pixScale ) ) ),
  14597. exp2( ceil( log2( pixScale ) ) )
  14598. );
  14599. // Compute alpha thresholds at our two noise scales
  14600. const alpha = vec2(
  14601. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  14602. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  14603. );
  14604. // Factor to interpolate lerp with
  14605. const lerpFactor = fract( log2( pixScale ) );
  14606. // Interpolate alpha threshold from noise at two scales
  14607. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  14608. // Pass into CDF to compute uniformly distrib threshold
  14609. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  14610. const cases = vec3(
  14611. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  14612. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  14613. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  14614. // Find our final, uniformly distributed alpha threshold (ατ)
  14615. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  14616. // Avoids ατ == 0. Could also do ατ =1-ατ
  14617. return clamp( threshold, 1.0e-6, 1.0 );
  14618. } ).setLayout( {
  14619. name: 'getAlphaHashThreshold',
  14620. type: 'float',
  14621. inputs: [
  14622. { name: 'position', type: 'vec3' }
  14623. ]
  14624. } );
  14625. /**
  14626. * An attribute node for representing vertex colors.
  14627. *
  14628. * @augments AttributeNode
  14629. */
  14630. class VertexColorNode extends AttributeNode {
  14631. static get type() {
  14632. return 'VertexColorNode';
  14633. }
  14634. /**
  14635. * Constructs a new vertex color node.
  14636. *
  14637. * @param {number} index - The attribute index.
  14638. */
  14639. constructor( index ) {
  14640. super( null, 'vec4' );
  14641. /**
  14642. * This flag can be used for type testing.
  14643. *
  14644. * @type {boolean}
  14645. * @readonly
  14646. * @default true
  14647. */
  14648. this.isVertexColorNode = true;
  14649. /**
  14650. * The attribute index to enable more than one sets of vertex colors.
  14651. *
  14652. * @type {number}
  14653. * @default 0
  14654. */
  14655. this.index = index;
  14656. }
  14657. /**
  14658. * Overwrites the default implementation by honoring the attribute index.
  14659. *
  14660. * @param {NodeBuilder} builder - The current node builder.
  14661. * @return {string} The attribute name.
  14662. */
  14663. getAttributeName( /*builder*/ ) {
  14664. const index = this.index;
  14665. return 'color' + ( index > 0 ? index : '' );
  14666. }
  14667. generate( builder ) {
  14668. const attributeName = this.getAttributeName( builder );
  14669. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  14670. let result;
  14671. if ( geometryAttribute === true ) {
  14672. result = super.generate( builder );
  14673. } else {
  14674. // Vertex color fallback should be white
  14675. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  14676. }
  14677. return result;
  14678. }
  14679. serialize( data ) {
  14680. super.serialize( data );
  14681. data.index = this.index;
  14682. }
  14683. deserialize( data ) {
  14684. super.deserialize( data );
  14685. this.index = data.index;
  14686. }
  14687. }
  14688. /**
  14689. * TSL function for creating a reference node.
  14690. *
  14691. * @tsl
  14692. * @function
  14693. * @param {number} [index=0] - The attribute index.
  14694. * @returns {VertexColorNode}
  14695. */
  14696. const vertexColor = ( index = 0 ) => new VertexColorNode( index );
  14697. /**
  14698. * Base class for all node materials.
  14699. *
  14700. * @augments Material
  14701. */
  14702. class NodeMaterial extends Material {
  14703. static get type() {
  14704. return 'NodeMaterial';
  14705. }
  14706. /**
  14707. * Represents the type of the node material.
  14708. *
  14709. * @type {string}
  14710. */
  14711. get type() {
  14712. return this.constructor.type;
  14713. }
  14714. set type( _value ) { /* */ }
  14715. /**
  14716. * Constructs a new node material.
  14717. */
  14718. constructor() {
  14719. super();
  14720. /**
  14721. * This flag can be used for type testing.
  14722. *
  14723. * @type {boolean}
  14724. * @readonly
  14725. * @default true
  14726. */
  14727. this.isNodeMaterial = true;
  14728. /**
  14729. * Whether this material is affected by fog or not.
  14730. *
  14731. * @type {boolean}
  14732. * @default true
  14733. */
  14734. this.fog = true;
  14735. /**
  14736. * Whether this material is affected by lights or not.
  14737. *
  14738. * @type {boolean}
  14739. * @default false
  14740. */
  14741. this.lights = false;
  14742. /**
  14743. * Node materials which set their `lights` property to `true`
  14744. * are affected by all lights of the scene. Sometimes selective
  14745. * lighting is wanted which means only _some_ lights in the scene
  14746. * affect a material. This can be achieved by creating an instance
  14747. * of {@link LightsNode} with a list of selective
  14748. * lights and assign the node to this property.
  14749. *
  14750. * ```js
  14751. * const customLightsNode = lights( [ light1, light2 ] );
  14752. * material.lightsNode = customLightsNode;
  14753. * ```
  14754. *
  14755. * @type {?LightsNode}
  14756. * @default null
  14757. */
  14758. this.lightsNode = null;
  14759. /**
  14760. * The environment of node materials can be defined by an environment
  14761. * map assigned to the `envMap` property or by `Scene.environment`
  14762. * if the node material is a PBR material. This node property allows to overwrite
  14763. * the default behavior and define the environment with a custom node.
  14764. *
  14765. * ```js
  14766. * material.envNode = pmremTexture( renderTarget.texture );
  14767. * ```
  14768. *
  14769. * @type {?Node<vec3>}
  14770. * @default null
  14771. */
  14772. this.envNode = null;
  14773. /**
  14774. * The lighting of node materials might be influenced by ambient occlusion.
  14775. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  14776. * and the respective `aoMapIntensity`. This node property allows to overwrite
  14777. * the default and define the ambient occlusion with a custom node instead.
  14778. *
  14779. * If you don't want to overwrite the diffuse color but modify the existing
  14780. * values instead, use {@link materialAO}.
  14781. *
  14782. * @type {?Node<float>}
  14783. * @default null
  14784. */
  14785. this.aoNode = null;
  14786. /**
  14787. * The diffuse color of node materials is by default inferred from the
  14788. * `color` and `map` properties. This node property allows to overwrite the default
  14789. * and define the diffuse color with a node instead.
  14790. *
  14791. * ```js
  14792. * material.colorNode = color( 0xff0000 ); // define red color
  14793. * ```
  14794. *
  14795. * If you don't want to overwrite the diffuse color but modify the existing
  14796. * values instead, use {@link materialColor}.
  14797. *
  14798. * ```js
  14799. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  14800. * ```
  14801. *
  14802. * @type {?Node<vec3>}
  14803. * @default null
  14804. */
  14805. this.colorNode = null;
  14806. /**
  14807. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  14808. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  14809. * and define the normals with a node instead.
  14810. *
  14811. * If you don't want to overwrite the normals but modify the existing values instead,
  14812. * use {@link materialNormal}.
  14813. *
  14814. * @type {?Node<vec3>}
  14815. * @default null
  14816. */
  14817. this.normalNode = null;
  14818. /**
  14819. * The opacity of node materials is by default inferred from the `opacity`
  14820. * and `alphaMap` properties. This node property allows to overwrite the default
  14821. * and define the opacity with a node instead.
  14822. *
  14823. * If you don't want to overwrite the opacity but modify the existing
  14824. * value instead, use {@link materialOpacity}.
  14825. *
  14826. * @type {?Node<float>}
  14827. * @default null
  14828. */
  14829. this.opacityNode = null;
  14830. /**
  14831. * This node can be used to implement a variety of filter-like effects. The idea is
  14832. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  14833. * to create an arbitrary effect and then assign the node composition to this property.
  14834. * Everything behind the object using this material will now be affected by a filter.
  14835. *
  14836. * ```js
  14837. * const material = new NodeMaterial()
  14838. * material.transparent = true;
  14839. *
  14840. * // everything behind the object will be monochromatic
  14841. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  14842. * ```
  14843. *
  14844. * Backdrop computations are part of the lighting so only lit materials can use this property.
  14845. *
  14846. * @type {?Node<vec3>}
  14847. * @default null
  14848. */
  14849. this.backdropNode = null;
  14850. /**
  14851. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  14852. *
  14853. * @type {?Node<float>}
  14854. * @default null
  14855. */
  14856. this.backdropAlphaNode = null;
  14857. /**
  14858. * The alpha test of node materials is by default inferred from the `alphaTest`
  14859. * property. This node property allows to overwrite the default and define the
  14860. * alpha test with a node instead.
  14861. *
  14862. * If you don't want to overwrite the alpha test but modify the existing
  14863. * value instead, use {@link materialAlphaTest}.
  14864. *
  14865. * @type {?Node<float>}
  14866. * @default null
  14867. */
  14868. this.alphaTestNode = null;
  14869. /**
  14870. * Discards the fragment if the mask value is `false`.
  14871. *
  14872. * @type {?Node<bool>}
  14873. * @default null
  14874. */
  14875. this.maskNode = null;
  14876. /**
  14877. * This node can be used to implement a shadow mask for the material.
  14878. *
  14879. * @type {?Node<bool>}
  14880. * @default null
  14881. */
  14882. this.maskShadowNode = null;
  14883. /**
  14884. * The local vertex positions are computed based on multiple factors like the
  14885. * attribute data, morphing or skinning. This node property allows to overwrite
  14886. * the default and define local vertex positions with nodes instead.
  14887. *
  14888. * If you don't want to overwrite the vertex positions but modify the existing
  14889. * values instead, use {@link positionLocal}.
  14890. *
  14891. *```js
  14892. * material.positionNode = positionLocal.add( displace );
  14893. * ```
  14894. *
  14895. * @type {?Node<vec3>}
  14896. * @default null
  14897. */
  14898. this.positionNode = null;
  14899. /**
  14900. * This node property is intended for logic which modifies geometry data once or per animation step.
  14901. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  14902. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  14903. * can be implemented.
  14904. *
  14905. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  14906. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  14907. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  14908. * eventually assigned to `geometryNode`.
  14909. *
  14910. * @type {?Function}
  14911. * @default null
  14912. */
  14913. this.geometryNode = null;
  14914. /**
  14915. * Allows to overwrite depth values in the fragment shader.
  14916. *
  14917. * @type {?Node<float>}
  14918. * @default null
  14919. */
  14920. this.depthNode = null;
  14921. /**
  14922. * Allows to overwrite the position used for shadow map rendering which
  14923. * is by default {@link positionWorld}, the vertex position
  14924. * in world space.
  14925. *
  14926. * @type {?Node<float>}
  14927. * @default null
  14928. */
  14929. this.receivedShadowPositionNode = null;
  14930. /**
  14931. * Allows to overwrite the geometry position used for shadow map projection which
  14932. * is by default {@link positionLocal}, the vertex position in local space.
  14933. *
  14934. * @type {?Node<float>}
  14935. * @default null
  14936. */
  14937. this.castShadowPositionNode = null;
  14938. /**
  14939. * This node can be used to influence how an object using this node material
  14940. * receive shadows.
  14941. *
  14942. * ```js
  14943. * const totalShadows = float( 1 ).toVar();
  14944. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  14945. * totalShadows.mulAssign( shadow );
  14946. * //return float( 1 ); // bypass received shadows
  14947. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  14948. * } );
  14949. *
  14950. * @type {?(Function|FunctionNode<vec4>)}
  14951. * @default null
  14952. */
  14953. this.receivedShadowNode = null;
  14954. /**
  14955. * This node can be used to influence how an object using this node material
  14956. * casts shadows. To apply a color to shadows, you can simply do:
  14957. *
  14958. * ```js
  14959. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  14960. * ```
  14961. *
  14962. * Which can be nice to fake colored shadows of semi-transparent objects. It
  14963. * is also common to use the property with `Fn` function so checks are performed
  14964. * per fragment.
  14965. *
  14966. * ```js
  14967. * materialCustomShadow.castShadowNode = Fn( () => {
  14968. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  14969. * return materialColor;
  14970. * } )();
  14971. * ```
  14972. *
  14973. * @type {?Node<vec4>}
  14974. * @default null
  14975. */
  14976. this.castShadowNode = null;
  14977. /**
  14978. * This node can be used to define the final output of the material.
  14979. *
  14980. * TODO: Explain the differences to `fragmentNode`.
  14981. *
  14982. * @type {?Node<vec4>}
  14983. * @default null
  14984. */
  14985. this.outputNode = null;
  14986. /**
  14987. * MRT configuration is done on renderer or pass level. This node allows to
  14988. * overwrite what values are written into MRT targets on material level. This
  14989. * can be useful for implementing selective FX features that should only affect
  14990. * specific objects.
  14991. *
  14992. * @type {?MRTNode}
  14993. * @default null
  14994. */
  14995. this.mrtNode = null;
  14996. /**
  14997. * This node property can be used if you need complete freedom in implementing
  14998. * the fragment shader. Assigning a node will replace the built-in material
  14999. * logic used in the fragment stage.
  15000. *
  15001. * @type {?Node<vec4>}
  15002. * @default null
  15003. */
  15004. this.fragmentNode = null;
  15005. /**
  15006. * This node property can be used if you need complete freedom in implementing
  15007. * the vertex shader. Assigning a node will replace the built-in material logic
  15008. * used in the vertex stage.
  15009. *
  15010. * @type {?Node<vec4>}
  15011. * @default null
  15012. */
  15013. this.vertexNode = null;
  15014. /**
  15015. * This node can be used as a global context management component for this material.
  15016. *
  15017. * @type {?ContextNode}
  15018. * @default null
  15019. */
  15020. this.contextNode = null;
  15021. }
  15022. /**
  15023. * Returns an array of child nodes for this material.
  15024. *
  15025. * @private
  15026. * @returns {Array<{property: string, childNode: Node}>}
  15027. */
  15028. _getNodeChildren() {
  15029. const children = [];
  15030. for ( const property of Object.getOwnPropertyNames( this ) ) {
  15031. if ( property.startsWith( '_' ) === true ) continue;
  15032. const object = this[ property ];
  15033. if ( object && object.isNode === true ) {
  15034. children.push( { property, childNode: object } );
  15035. }
  15036. }
  15037. return children;
  15038. }
  15039. /**
  15040. * Allows to define a custom cache key that influence the material key computation
  15041. * for render objects.
  15042. *
  15043. * @return {string} The custom cache key.
  15044. */
  15045. customProgramCacheKey() {
  15046. const values = [];
  15047. for ( const { property, childNode } of this._getNodeChildren() ) {
  15048. values.push( hashString( property.slice( 0, -4 ) ), childNode.getCacheKey() );
  15049. }
  15050. return this.type + hashArray( values );
  15051. }
  15052. /**
  15053. * Builds this material with the given node builder.
  15054. *
  15055. * @param {NodeBuilder} builder - The current node builder.
  15056. */
  15057. build( builder ) {
  15058. this.setup( builder );
  15059. }
  15060. /**
  15061. * Setups a node material observer with the given builder.
  15062. *
  15063. * @param {NodeBuilder} builder - The current node builder.
  15064. * @return {NodeMaterialObserver} The node material observer.
  15065. */
  15066. setupObserver( builder ) {
  15067. return new NodeMaterialObserver( builder );
  15068. }
  15069. /**
  15070. * Setups the vertex and fragment stage of this node material.
  15071. *
  15072. * @param {NodeBuilder} builder - The current node builder.
  15073. */
  15074. setup( builder ) {
  15075. builder.context.setupNormal = () => subBuild( this.setupNormal( builder ), 'NORMAL', 'vec3' );
  15076. builder.context.setupPositionView = () => this.setupPositionView( builder );
  15077. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  15078. const renderer = builder.renderer;
  15079. const renderTarget = renderer.getRenderTarget();
  15080. // < VERTEX STAGE >
  15081. builder.addStack();
  15082. const mvp = this.setupVertex( builder );
  15083. const vertexNode = subBuild( this.vertexNode || mvp, 'VERTEX' );
  15084. builder.context.clipSpace = vertexNode;
  15085. builder.stack.outputNode = vertexNode;
  15086. this.setupHardwareClipping( builder );
  15087. if ( this.geometryNode !== null ) {
  15088. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  15089. }
  15090. builder.addFlow( 'vertex', builder.removeStack() );
  15091. // < FRAGMENT STAGE >
  15092. builder.addStack();
  15093. let resultNode;
  15094. const clippingNode = this.setupClipping( builder );
  15095. if ( this.depthWrite === true || this.depthTest === true ) {
  15096. // only write depth if depth buffer is configured
  15097. if ( renderTarget !== null ) {
  15098. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  15099. } else {
  15100. if ( renderer.depth === true ) this.setupDepth( builder );
  15101. }
  15102. }
  15103. if ( this.fragmentNode === null ) {
  15104. this.setupDiffuseColor( builder );
  15105. this.setupAmbientOcclusion( builder );
  15106. this.setupVariants( builder );
  15107. const outgoingLightNode = this.setupLighting( builder );
  15108. if ( clippingNode !== null ) builder.stack.addToStack( clippingNode );
  15109. // force unsigned floats - useful for RenderTargets
  15110. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  15111. resultNode = this.setupOutput( builder, basicOutput );
  15112. // OUTPUT NODE
  15113. output.assign( resultNode );
  15114. //
  15115. const isCustomOutput = this.outputNode !== null;
  15116. if ( isCustomOutput ) resultNode = this.outputNode;
  15117. //
  15118. if ( builder.context.getOutput ) {
  15119. resultNode = builder.context.getOutput( resultNode, builder );
  15120. }
  15121. // MRT
  15122. if ( renderTarget !== null ) {
  15123. const mrt = renderer.getMRT();
  15124. const materialMRT = this.mrtNode;
  15125. if ( mrt !== null ) {
  15126. if ( isCustomOutput ) output.assign( resultNode );
  15127. resultNode = mrt;
  15128. if ( materialMRT !== null ) {
  15129. resultNode = mrt.merge( materialMRT );
  15130. }
  15131. } else if ( materialMRT !== null ) {
  15132. resultNode = materialMRT;
  15133. }
  15134. }
  15135. } else {
  15136. let fragmentNode = this.fragmentNode;
  15137. if ( fragmentNode.isOutputStructNode !== true ) {
  15138. fragmentNode = fragmentNode.convert( builder.getOutputType() );
  15139. }
  15140. resultNode = this.setupOutput( builder, fragmentNode );
  15141. }
  15142. builder.stack.outputNode = resultNode;
  15143. builder.addFlow( 'fragment', builder.removeStack() );
  15144. // < OBSERVER >
  15145. builder.observer = this.setupObserver( builder );
  15146. }
  15147. /**
  15148. * Setups the clipping node.
  15149. *
  15150. * @param {NodeBuilder} builder - The current node builder.
  15151. * @return {ClippingNode} The clipping node.
  15152. */
  15153. setupClipping( builder ) {
  15154. if ( builder.clippingContext === null ) return null;
  15155. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  15156. let result = null;
  15157. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  15158. const samples = builder.renderer.currentSamples;
  15159. if ( this.alphaToCoverage && samples > 1 ) {
  15160. // to be added to flow when the color/alpha value has been determined
  15161. result = clippingAlpha();
  15162. } else {
  15163. builder.stack.addToStack( clipping() );
  15164. }
  15165. }
  15166. return result;
  15167. }
  15168. /**
  15169. * Setups the hardware clipping if available on the current device.
  15170. *
  15171. * @param {NodeBuilder} builder - The current node builder.
  15172. */
  15173. setupHardwareClipping( builder ) {
  15174. builder.hardwareClipping = false;
  15175. if ( builder.clippingContext === null ) return;
  15176. const candidateCount = builder.clippingContext.unionPlanes.length;
  15177. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  15178. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  15179. builder.stack.addToStack( hardwareClipping() );
  15180. builder.hardwareClipping = true;
  15181. }
  15182. return;
  15183. }
  15184. /**
  15185. * Setups the depth of this material.
  15186. *
  15187. * @param {NodeBuilder} builder - The current node builder.
  15188. */
  15189. setupDepth( builder ) {
  15190. const { renderer, camera } = builder;
  15191. // Depth
  15192. let depthNode = this.depthNode;
  15193. if ( depthNode === null ) {
  15194. const mrt = renderer.getMRT();
  15195. if ( mrt && mrt.has( 'depth' ) ) {
  15196. depthNode = mrt.get( 'depth' );
  15197. } else if ( renderer.logarithmicDepthBuffer === true ) {
  15198. if ( camera.isPerspectiveCamera ) {
  15199. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  15200. } else {
  15201. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  15202. }
  15203. }
  15204. }
  15205. if ( depthNode !== null ) {
  15206. depth.assign( depthNode ).toStack();
  15207. }
  15208. }
  15209. /**
  15210. * Setups the position node in view space. This method exists
  15211. * so derived node materials can modify the implementation e.g. sprite materials.
  15212. *
  15213. * @param {NodeBuilder} builder - The current node builder.
  15214. * @return {Node<vec3>} The position in view space.
  15215. */
  15216. setupPositionView( /*builder*/ ) {
  15217. return modelViewMatrix.mul( positionLocal ).xyz;
  15218. }
  15219. /**
  15220. * Setups the position in clip space.
  15221. *
  15222. * @param {NodeBuilder} builder - The current node builder.
  15223. * @return {Node<vec4>} The position in view space.
  15224. */
  15225. setupModelViewProjection( /*builder*/ ) {
  15226. return cameraProjectionMatrix.mul( positionView );
  15227. }
  15228. /**
  15229. * Setups the logic for the vertex stage.
  15230. *
  15231. * @param {NodeBuilder} builder - The current node builder.
  15232. * @return {Node<vec4>} The position in clip space.
  15233. */
  15234. setupVertex( builder ) {
  15235. builder.addStack();
  15236. this.setupPosition( builder );
  15237. builder.context.position = builder.removeStack();
  15238. return modelViewProjection;
  15239. }
  15240. /**
  15241. * Setups the computation of the position in local space.
  15242. *
  15243. * @param {NodeBuilder} builder - The current node builder.
  15244. * @return {Node<vec3>} The position in local space.
  15245. */
  15246. setupPosition( builder ) {
  15247. const { object, geometry } = builder;
  15248. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  15249. morphReference( object );
  15250. }
  15251. if ( object.isSkinnedMesh === true ) {
  15252. skinning( object );
  15253. }
  15254. if ( this.displacementMap ) {
  15255. const displacementMap = materialReference( 'displacementMap', 'texture' );
  15256. const displacementScale = materialReference( 'displacementScale', 'float' );
  15257. const displacementBias = materialReference( 'displacementBias', 'float' );
  15258. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  15259. }
  15260. if ( object.isBatchedMesh ) {
  15261. batch( object );
  15262. }
  15263. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  15264. instancedMesh( object );
  15265. }
  15266. if ( this.positionNode !== null ) {
  15267. positionLocal.assign( subBuild( this.positionNode, 'POSITION', 'vec3' ) );
  15268. }
  15269. return positionLocal;
  15270. }
  15271. /**
  15272. * Setups the computation of the material's diffuse color.
  15273. *
  15274. * @param {NodeBuilder} builder - The current node builder.
  15275. * @param {BufferGeometry} geometry - The geometry.
  15276. */
  15277. setupDiffuseColor( builder ) {
  15278. const { object, geometry } = builder;
  15279. // MASK
  15280. if ( this.maskNode !== null ) {
  15281. // Discard if the mask is `false`
  15282. bool( this.maskNode ).not().discard();
  15283. }
  15284. // COLOR
  15285. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  15286. // VERTEX COLORS
  15287. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  15288. colorNode = colorNode.mul( vertexColor() );
  15289. }
  15290. // INSTANCED COLORS
  15291. if ( object.instanceColor ) {
  15292. colorNode = instanceColor.mul( colorNode );
  15293. }
  15294. if ( object.isBatchedMesh && object._colorsTexture ) {
  15295. colorNode = batchColor.mul( colorNode );
  15296. }
  15297. // DIFFUSE COLOR
  15298. diffuseColor.assign( colorNode );
  15299. // OPACITY
  15300. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  15301. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  15302. // ALPHA TEST
  15303. let alphaTestNode = null;
  15304. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  15305. alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  15306. if ( this.alphaToCoverage === true ) {
  15307. diffuseColor.a = smoothstep( alphaTestNode, alphaTestNode.add( fwidth( diffuseColor.a ) ), diffuseColor.a );
  15308. diffuseColor.a.lessThanEqual( 0 ).discard();
  15309. } else {
  15310. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  15311. }
  15312. }
  15313. // ALPHA HASH
  15314. if ( this.alphaHash === true ) {
  15315. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  15316. }
  15317. // OPAQUE
  15318. if ( builder.isOpaque() ) {
  15319. diffuseColor.a.assign( 1.0 );
  15320. }
  15321. }
  15322. /**
  15323. * Abstract interface method that can be implemented by derived materials
  15324. * to setup material-specific node variables.
  15325. *
  15326. * @abstract
  15327. * @param {NodeBuilder} builder - The current node builder.
  15328. */
  15329. setupVariants( /*builder*/ ) {
  15330. // Interface function.
  15331. }
  15332. /**
  15333. * Setups the outgoing light node variable
  15334. *
  15335. * @return {Node<vec3>} The outgoing light node.
  15336. */
  15337. setupOutgoingLight() {
  15338. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  15339. }
  15340. /**
  15341. * Setups the normal node from the material.
  15342. *
  15343. * @return {Node<vec3>} The normal node.
  15344. */
  15345. setupNormal() {
  15346. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  15347. }
  15348. /**
  15349. * Setups the environment node from the material.
  15350. *
  15351. * @param {NodeBuilder} builder - The current node builder.
  15352. * @return {Node<vec4>} The environment node.
  15353. */
  15354. setupEnvironment( /*builder*/ ) {
  15355. let node = null;
  15356. if ( this.envNode ) {
  15357. node = this.envNode;
  15358. } else if ( this.envMap ) {
  15359. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  15360. }
  15361. return node;
  15362. }
  15363. /**
  15364. * Setups the light map node from the material.
  15365. *
  15366. * @param {NodeBuilder} builder - The current node builder.
  15367. * @return {Node<vec3>} The light map node.
  15368. */
  15369. setupLightMap( builder ) {
  15370. let node = null;
  15371. if ( builder.material.lightMap ) {
  15372. node = new IrradianceNode( materialLightMap );
  15373. }
  15374. return node;
  15375. }
  15376. /**
  15377. * Setups the lights node based on the scene, environment and material.
  15378. *
  15379. * @param {NodeBuilder} builder - The current node builder.
  15380. * @return {LightingNode<Array>} The lights node.
  15381. */
  15382. setupMaterialLightings( builder ) {
  15383. const materialLightsNode = [];
  15384. if ( builder.renderer.lighting.enabled === false ) {
  15385. return materialLightsNode;
  15386. }
  15387. //
  15388. const envNode = this.setupEnvironment( builder );
  15389. if ( envNode && envNode.isLightingNode ) {
  15390. materialLightsNode.push( envNode );
  15391. }
  15392. const lightMapNode = this.setupLightMap( builder );
  15393. if ( lightMapNode && lightMapNode.isLightingNode ) {
  15394. materialLightsNode.push( lightMapNode );
  15395. }
  15396. if ( builder.context.ambientOcclusion ) {
  15397. materialLightsNode.push( new AONode( builder.context.ambientOcclusion ) );
  15398. }
  15399. return materialLightsNode;
  15400. }
  15401. /**
  15402. * Setups the ambient occlusion node from the material.
  15403. *
  15404. * @param {NodeBuilder} builder - The current node builder.
  15405. * @return {Node} The ambient occlusion node.
  15406. */
  15407. setupAmbientOcclusion( builder ) {
  15408. let aoNode = this.aoNode;
  15409. if ( aoNode === null && builder.material.aoMap ) {
  15410. aoNode = materialAO;
  15411. }
  15412. if ( builder.context.getAO ) {
  15413. aoNode = builder.context.getAO( aoNode, builder );
  15414. }
  15415. if ( aoNode !== null ) {
  15416. ambientOcclusion.assign( aoNode );
  15417. builder.context.ambientOcclusion = ambientOcclusion;
  15418. }
  15419. }
  15420. /**
  15421. * This method should be implemented by most derived materials
  15422. * since it defines the material's lighting model.
  15423. *
  15424. * @abstract
  15425. * @param {NodeBuilder} builder - The current node builder.
  15426. * @return {LightingModel} The lighting model.
  15427. */
  15428. setupLightingModel( /*builder*/ ) {
  15429. // Interface function.
  15430. }
  15431. /**
  15432. * Setups the outgoing light node.
  15433. *
  15434. * @param {NodeBuilder} builder - The current node builder.
  15435. * @return {Node<vec3>} The outgoing light node.
  15436. */
  15437. setupLighting( builder ) {
  15438. const { material } = builder;
  15439. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  15440. // OUTGOING LIGHT
  15441. const lights = this.lights === true || this.lightsNode !== null;
  15442. const materialLightings = this.lights === true ? this.setupMaterialLightings( builder ) : [];
  15443. const lightsNode = lights ? ( this.lightsNode || builder.lightsNode ) : null;
  15444. let outgoingLightNode = this.setupOutgoingLight( builder );
  15445. if ( lightsNode && ( materialLightings.length > 0 || lightsNode.getScope().hasLights ) ) {
  15446. const lightingModel = this.setupLightingModel( builder ) || null;
  15447. outgoingLightNode = lightingContext( lightsNode, lightingModel, materialLightings, backdropNode, backdropAlphaNode );
  15448. } else if ( backdropNode !== null ) {
  15449. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  15450. }
  15451. // EMISSIVE
  15452. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  15453. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  15454. outgoingLightNode = outgoingLightNode.add( emissive );
  15455. }
  15456. return outgoingLightNode;
  15457. }
  15458. /**
  15459. * Setup the fog.
  15460. *
  15461. * @param {NodeBuilder} builder - The current node builder.
  15462. * @param {Node<vec4>} outputNode - The existing output node.
  15463. * @return {Node<vec4>} The output node.
  15464. */
  15465. setupFog( builder, outputNode ) {
  15466. const fogNode = builder.fogNode;
  15467. if ( fogNode ) {
  15468. output.assign( outputNode );
  15469. outputNode = vec4( fogNode.toVar() );
  15470. }
  15471. return outputNode;
  15472. }
  15473. /**
  15474. * Setups premultiplied alpha.
  15475. *
  15476. * @param {NodeBuilder} builder - The current node builder.
  15477. * @param {Node<vec4>} outputNode - The existing output node.
  15478. * @return {Node<vec4>} The output node.
  15479. */
  15480. setupPremultipliedAlpha( builder, outputNode ) {
  15481. return premultiplyAlpha( outputNode );
  15482. }
  15483. /**
  15484. * Setups the output node.
  15485. *
  15486. * This method can be implemented by derived materials to extend the functionality
  15487. * of the material's output or replace it altogether.
  15488. *
  15489. * ```js
  15490. * class ColoredShadowMaterial extends MeshPhongNodeMaterial {
  15491. * constructor( parameters ) {
  15492. * super( parameters );
  15493. * this._shadeColor = uniform( new Color( parameters.shadeColor ?? 0xff0000 ) );
  15494. * }
  15495. *
  15496. * setupOutput( builder, outputNode ) {
  15497. * // Modify the native output of the MeshPhongNodeMaterial fragment shader
  15498. * const brightness = min( outputNode.r, 1.0 );
  15499. * const mixedColor = mix( this._shadeColor, diffuseColor.rgb, brightness );
  15500. * // Return new output back into NodeMaterial flow
  15501. * return super.setupOutput( builder, vec4( mixedColor, outputNode.a ) );
  15502. * }
  15503. * }
  15504. * ```
  15505. *
  15506. * @param {NodeBuilder} builder - The current node builder.
  15507. * @param {Node<vec4>} outputNode - The existing output node.
  15508. * @return {Node<vec4>} The output node.
  15509. */
  15510. setupOutput( builder, outputNode ) {
  15511. // FOG
  15512. if ( this.fog === true ) {
  15513. outputNode = this.setupFog( builder, outputNode );
  15514. }
  15515. // PREMULTIPLIED ALPHA
  15516. if ( this.premultipliedAlpha === true ) {
  15517. outputNode = this.setupPremultipliedAlpha( builder, outputNode );
  15518. }
  15519. return outputNode;
  15520. }
  15521. /**
  15522. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  15523. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  15524. * defining all material properties of the classic type in the node type.
  15525. *
  15526. * @param {Material} material - The material to copy properties with their values to this node material.
  15527. */
  15528. setDefaultValues( material ) {
  15529. // This approach is to reuse the native refreshUniforms*
  15530. // and turn available the use of features like transmission and environment in core
  15531. for ( const property in material ) {
  15532. const value = material[ property ];
  15533. if ( this[ property ] === undefined ) {
  15534. this[ property ] = value;
  15535. if ( value && value.clone ) this[ property ] = value.clone();
  15536. }
  15537. }
  15538. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  15539. for ( const key in descriptors ) {
  15540. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined && descriptors[ key ].get !== undefined ) {
  15541. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  15542. }
  15543. }
  15544. }
  15545. /**
  15546. * Serializes this material to JSON.
  15547. *
  15548. * @param {?(Object|string)} meta - The meta information for serialization.
  15549. * @return {Object} The serialized node.
  15550. */
  15551. toJSON( meta ) {
  15552. const isRoot = ( meta === undefined || typeof meta === 'string' );
  15553. if ( isRoot ) {
  15554. meta = {
  15555. textures: {},
  15556. images: {},
  15557. nodes: {}
  15558. };
  15559. }
  15560. const data = Material.prototype.toJSON.call( this, meta );
  15561. data.inputNodes = {};
  15562. for ( const { property, childNode } of this._getNodeChildren() ) {
  15563. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  15564. }
  15565. // TODO: Copied from Object3D.toJSON
  15566. function extractFromCache( cache ) {
  15567. const values = [];
  15568. for ( const key in cache ) {
  15569. const data = cache[ key ];
  15570. delete data.metadata;
  15571. values.push( data );
  15572. }
  15573. return values;
  15574. }
  15575. if ( isRoot ) {
  15576. const textures = extractFromCache( meta.textures );
  15577. const images = extractFromCache( meta.images );
  15578. const nodes = extractFromCache( meta.nodes );
  15579. if ( textures.length > 0 ) data.textures = textures;
  15580. if ( images.length > 0 ) data.images = images;
  15581. if ( nodes.length > 0 ) data.nodes = nodes;
  15582. }
  15583. return data;
  15584. }
  15585. /**
  15586. * Copies the common properties of the given material to this instance.
  15587. *
  15588. * @param {Material} source - The material to copy.
  15589. * @return {NodeMaterial} A reference to this node material.
  15590. */
  15591. copy( source ) {
  15592. const descriptors = Object.getOwnPropertyDescriptors( this.constructor.prototype );
  15593. for ( const property in descriptors ) {
  15594. if ( descriptors[ property ].set !== undefined && source[ property ] !== undefined ) {
  15595. const value = source[ property ];
  15596. if ( this[ property ] && this[ property ].copy !== undefined ) {
  15597. this[ property ].copy( value );
  15598. } else {
  15599. this[ property ] = value;
  15600. }
  15601. }
  15602. }
  15603. for ( const property in this ) {
  15604. // Skip internal/private properties (starting with '_'), flags (starting with 'is' + uppercase),
  15605. // and properties that are handled separately or should not be copied (id, uuid, version, type, userData, clippingPlanes).
  15606. if ( /^(?:is[A-Z]|_)|^(?:id|uuid|version|type|userData|clippingPlanes)$/.test( property ) ) continue;
  15607. if ( this[ property ] !== undefined && source[ property ] !== undefined ) {
  15608. const value = source[ property ];
  15609. if ( this[ property ] && this[ property ].copy !== undefined ) {
  15610. this[ property ].copy( value );
  15611. } else {
  15612. this[ property ] = value;
  15613. }
  15614. }
  15615. }
  15616. this.clippingPlanes = source.clippingPlanes ? source.clippingPlanes.map( ( plane ) => plane.clone() ) : null;
  15617. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  15618. return this;
  15619. }
  15620. }
  15621. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  15622. /**
  15623. * Node material version of {@link LineBasicMaterial}.
  15624. *
  15625. * @augments NodeMaterial
  15626. */
  15627. class LineBasicNodeMaterial extends NodeMaterial {
  15628. static get type() {
  15629. return 'LineBasicNodeMaterial';
  15630. }
  15631. /**
  15632. * Constructs a new line basic node material.
  15633. *
  15634. * @param {Object} [parameters] - The configuration parameter.
  15635. */
  15636. constructor( parameters ) {
  15637. super();
  15638. /**
  15639. * This flag can be used for type testing.
  15640. *
  15641. * @type {boolean}
  15642. * @readonly
  15643. * @default true
  15644. */
  15645. this.isLineBasicNodeMaterial = true;
  15646. this.setDefaultValues( _defaultValues$d );
  15647. this.setValues( parameters );
  15648. }
  15649. }
  15650. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  15651. /**
  15652. * Node material version of {@link LineDashedMaterial}.
  15653. *
  15654. * @augments NodeMaterial
  15655. */
  15656. class LineDashedNodeMaterial extends NodeMaterial {
  15657. static get type() {
  15658. return 'LineDashedNodeMaterial';
  15659. }
  15660. /**
  15661. * Constructs a new line dashed node material.
  15662. *
  15663. * @param {Object} [parameters] - The configuration parameter.
  15664. */
  15665. constructor( parameters ) {
  15666. super();
  15667. /**
  15668. * This flag can be used for type testing.
  15669. *
  15670. * @type {boolean}
  15671. * @readonly
  15672. * @default true
  15673. */
  15674. this.isLineDashedNodeMaterial = true;
  15675. this.setDefaultValues( _defaultValues$c );
  15676. /**
  15677. * The dash offset.
  15678. *
  15679. * @type {number}
  15680. * @default 0
  15681. */
  15682. this.dashOffset = 0;
  15683. /**
  15684. * The offset of dash materials is by default inferred from the `dashOffset`
  15685. * property. This node property allows to overwrite the default
  15686. * and define the offset with a node instead.
  15687. *
  15688. * If you don't want to overwrite the offset but modify the existing
  15689. * value instead, use {@link materialLineDashOffset}.
  15690. *
  15691. * @type {?Node<float>}
  15692. * @default null
  15693. */
  15694. this.offsetNode = null;
  15695. /**
  15696. * The scale of dash materials is by default inferred from the `scale`
  15697. * property. This node property allows to overwrite the default
  15698. * and define the scale with a node instead.
  15699. *
  15700. * If you don't want to overwrite the scale but modify the existing
  15701. * value instead, use {@link materialLineScale}.
  15702. *
  15703. * @type {?Node<float>}
  15704. * @default null
  15705. */
  15706. this.dashScaleNode = null;
  15707. /**
  15708. * The dash size of dash materials is by default inferred from the `dashSize`
  15709. * property. This node property allows to overwrite the default
  15710. * and define the dash size with a node instead.
  15711. *
  15712. * If you don't want to overwrite the dash size but modify the existing
  15713. * value instead, use {@link materialLineDashSize}.
  15714. *
  15715. * @type {?Node<float>}
  15716. * @default null
  15717. */
  15718. this.dashSizeNode = null;
  15719. /**
  15720. * The gap size of dash materials is by default inferred from the `gapSize`
  15721. * property. This node property allows to overwrite the default
  15722. * and define the gap size with a node instead.
  15723. *
  15724. * If you don't want to overwrite the gap size but modify the existing
  15725. * value instead, use {@link materialLineGapSize}.
  15726. *
  15727. * @type {?Node<float>}
  15728. * @default null
  15729. */
  15730. this.gapSizeNode = null;
  15731. this.setValues( parameters );
  15732. }
  15733. /**
  15734. * Setups the dash specific node variables.
  15735. *
  15736. * @param {NodeBuilder} builder - The current node builder.
  15737. */
  15738. setupVariants( /* builder */ ) {
  15739. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  15740. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  15741. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  15742. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  15743. dashSize.assign( dashSizeNode );
  15744. gapSize.assign( gapSizeNode );
  15745. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  15746. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  15747. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  15748. }
  15749. }
  15750. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  15751. /**
  15752. * Varying node representing the world position of the segment start in view space.
  15753. * Used for distance and coordinate calculations across the fragment shader.
  15754. * @type {VaryingNode<vec3>}
  15755. */
  15756. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  15757. /**
  15758. * Varying node representing the world position of the segment end in view space.
  15759. * Used for distance and coordinate calculations across the fragment shader.
  15760. * @type {VaryingNode<vec3>}
  15761. */
  15762. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  15763. /**
  15764. * Varying node representing the accumulated distance along the line.
  15765. * Crucial for correctly computing dashed line intervals in fragment stage.
  15766. * @type {VaryingNode<float>}
  15767. */
  15768. const lineDistance = varyingProperty( 'float', 'lineDistance' );
  15769. /**
  15770. * Varying node representing the interpolated world/view position of the current fragment.
  15771. * Used for line/ray distance checks under perspective projection.
  15772. * @type {VaryingNode<vec4>}
  15773. */
  15774. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  15775. /**
  15776. * Trims the line segment to avoid rendering behind the camera near plane.
  15777. * Computes an interpolation factor (alpha) to clamp the segment's coordinate.
  15778. *
  15779. * @param {Object} inputs
  15780. * @param {Node<vec4>} inputs.start - Segment start position in view space.
  15781. * @param {Node<vec4>} inputs.end - Segment end position in view space.
  15782. * @returns {Node<float>} The interpolation factor (alpha) to trim the segment.
  15783. */
  15784. const trimSegmentAlpha = Fn( ( { start, end } ) => {
  15785. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  15786. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  15787. // we need different nearEstimate formula for reversed and default depth buffer
  15788. // a is positive with a reversed depth buffer so it can be used for controlling the code flow
  15789. const nearEstimate = a.greaterThan( 0 ).select( b.negate().div( a.add( 1 ) ), b.mul( -0.5 ).div( a ) );
  15790. return nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  15791. }, { start: 'vec4', end: 'vec4', return: 'float' } );
  15792. /**
  15793. * Calculates the closest points on two 3D lines.
  15794. * Used for perspective-correct line rendering and coordinates interpolation.
  15795. *
  15796. * @param {Object} inputs
  15797. * @param {Node<vec3>} inputs.p1 - Start of line 1.
  15798. * @param {Node<vec3>} inputs.p2 - End of line 1.
  15799. * @param {Node<vec3>} inputs.p3 - Start of line 2.
  15800. * @param {Node<vec3>} inputs.p4 - End of line 2.
  15801. * @returns {Node<vec2>} A vec2 containing the parametric coordinates (mua, mub) of the closest points on line 1 and line 2.
  15802. */
  15803. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  15804. const p13 = p1.sub( p3 );
  15805. const p43 = p4.sub( p3 );
  15806. const p21 = p2.sub( p1 );
  15807. const d1343 = p13.dot( p43 );
  15808. const d4321 = p43.dot( p21 );
  15809. const d1321 = p13.dot( p21 );
  15810. const d4343 = p43.dot( p43 );
  15811. const d2121 = p21.dot( p21 );
  15812. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  15813. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  15814. const mua = numer.div( denom ).clamp();
  15815. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  15816. return vec2( mua, mub );
  15817. }, { p1: 'vec3', p2: 'vec3', p3: 'vec3', p4: 'vec3', return: 'vec2' } );
  15818. /**
  15819. * TSL node acting as a custom Model-View-Projection (MVP) for fat lines,
  15820. * expanding 3D segments into screen/world-facing ribbons of a specified width.
  15821. *
  15822. * @tsl
  15823. * @type {Node<vec4>}
  15824. */
  15825. const mvpLine = Fn( ( { material } ) => {
  15826. const useDash = material._useDash;
  15827. const useWorldUnits = material._useWorldUnits;
  15828. const instanceStart = attribute( 'instanceStart' );
  15829. const instanceEnd = attribute( 'instanceEnd' );
  15830. // camera space
  15831. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  15832. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  15833. let distanceStart, distanceEnd;
  15834. if ( useDash ) {
  15835. distanceStart = float( attribute( 'instanceDistanceStart' ) ).toVar( 'distanceStart' );
  15836. distanceEnd = float( attribute( 'instanceDistanceEnd' ) ).toVar( 'distanceEnd' );
  15837. }
  15838. if ( useWorldUnits ) {
  15839. worldStart.assign( start.xyz );
  15840. worldEnd.assign( end.xyz );
  15841. }
  15842. const aspect = viewport.z.div( viewport.w );
  15843. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  15844. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  15845. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  15846. // perhaps there is a more elegant solution -- WestLangley
  15847. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  15848. If( perspective, () => {
  15849. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  15850. const alpha = trimSegmentAlpha( { start, end } );
  15851. end.assign( vec4( mix( start.xyz, end.xyz, alpha ), end.w ) );
  15852. if ( useDash ) {
  15853. distanceEnd.assign( mix( distanceStart, distanceEnd, alpha ) );
  15854. }
  15855. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  15856. const alpha = trimSegmentAlpha( { start: end, end: start } );
  15857. start.assign( vec4( mix( end.xyz, start.xyz, alpha ), start.w ) );
  15858. if ( useDash ) {
  15859. distanceStart.assign( mix( distanceEnd, distanceStart, alpha ) );
  15860. }
  15861. } );
  15862. } );
  15863. if ( useDash ) {
  15864. const dashScaleNode = material.dashScaleNode ? float( material.dashScaleNode ) : materialLineScale;
  15865. const offsetNode = material.offsetNode ? float( material.offsetNode ) : materialLineDashOffset;
  15866. let lineDist = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( distanceStart ), dashScaleNode.mul( distanceEnd ) );
  15867. lineDist = lineDist.add( offsetNode );
  15868. lineDistance.assign( lineDist );
  15869. }
  15870. // clip space
  15871. const clipStart = cameraProjectionMatrix.mul( start );
  15872. const clipEnd = cameraProjectionMatrix.mul( end );
  15873. // ndc space
  15874. const ndcStart = clipStart.xyz.div( clipStart.w );
  15875. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  15876. // direction
  15877. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  15878. // account for clip-space aspect ratio
  15879. dir.x.assign( dir.x.mul( aspect ) );
  15880. dir.assign( dir.normalize() );
  15881. const clip = vec4().toVar();
  15882. if ( useWorldUnits ) {
  15883. // get the offset direction as perpendicular to the view vector
  15884. const worldDir = end.xyz.sub( start.xyz ).normalize();
  15885. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  15886. const worldUp = worldDir.cross( tmpFwd ).normalize();
  15887. const worldFwd = worldDir.cross( worldUp );
  15888. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  15889. // height offset
  15890. const hw = materialLineWidth.mul( 0.5 );
  15891. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  15892. // don't extend the line if we're rendering dashes because we
  15893. // won't be rendering the endcaps
  15894. if ( ! useDash ) {
  15895. // cap extension
  15896. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  15897. // add width to the box
  15898. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  15899. // endcaps
  15900. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  15901. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  15902. } );
  15903. }
  15904. // project the worldpos
  15905. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  15906. // shift the depth of the projected points so the line
  15907. // segments overlap neatly
  15908. const clipPose = vec3().toVar();
  15909. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  15910. clip.z.assign( clipPose.z.mul( clip.w ) );
  15911. } else {
  15912. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  15913. // undo aspect ratio adjustment
  15914. dir.x.assign( dir.x.div( aspect ) );
  15915. offset.x.assign( offset.x.div( aspect ) );
  15916. // sign flip
  15917. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  15918. // endcaps
  15919. If( positionGeometry.y.lessThan( 0.0 ), () => {
  15920. offset.assign( offset.sub( dir ) );
  15921. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  15922. offset.assign( offset.add( dir ) );
  15923. } );
  15924. // adjust for linewidth
  15925. offset.assign( offset.mul( materialLineWidth ) );
  15926. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  15927. offset.assign( offset.div( viewport.w.div( screenDPR ) ) );
  15928. // select end
  15929. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  15930. // back to clip space
  15931. offset.assign( offset.mul( clip.w ) );
  15932. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  15933. }
  15934. return clip;
  15935. } )();
  15936. /**
  15937. * TSL fragment node that computes the shape/coverage (alpha) of the fat line segment.
  15938. * Handles dash/gap generation, alpha-to-coverage rendering, and round endcaps.
  15939. *
  15940. * @tsl
  15941. * @type {Node<float>}
  15942. */
  15943. const alphaLine = Fn( ( { material, renderer } ) => {
  15944. const useAlphaToCoverage = material._useAlphaToCoverage;
  15945. const useDash = material._useDash;
  15946. const useWorldUnits = material._useWorldUnits;
  15947. const vUv = uv$1();
  15948. if ( useDash ) {
  15949. const dashSizeNode = material.dashSizeNode ? float( material.dashSizeNode ) : materialLineDashSize;
  15950. const gapSizeNode = material.gapSizeNode ? float( material.gapSizeNode ) : materialLineGapSize;
  15951. dashSize.assign( dashSizeNode );
  15952. gapSize.assign( gapSizeNode );
  15953. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  15954. lineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  15955. }
  15956. const alpha = float( 1 ).toVar( 'alpha' );
  15957. if ( useWorldUnits ) {
  15958. // Find the closest points on the view ray and the line segment
  15959. const rayEnd = worldPos.xyz.normalize().mul( 1e5 );
  15960. const lineDir = worldEnd.sub( worldStart );
  15961. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  15962. const p1 = worldStart.add( lineDir.mul( params.x ) );
  15963. const p2 = rayEnd.mul( params.y );
  15964. const delta = p1.sub( p2 );
  15965. const len = delta.length();
  15966. const norm = len.div( materialLineWidth );
  15967. if ( ! useDash ) {
  15968. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  15969. const dnorm = norm.fwidth();
  15970. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  15971. } else {
  15972. norm.greaterThan( 0.5 ).discard();
  15973. }
  15974. }
  15975. } else {
  15976. // round endcaps
  15977. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  15978. const a = vUv.x;
  15979. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  15980. const len2 = a.mul( a ).add( b.mul( b ) );
  15981. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  15982. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  15983. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  15984. } );
  15985. } else {
  15986. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  15987. const a = vUv.x;
  15988. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  15989. const len2 = a.mul( a ).add( b.mul( b ) );
  15990. len2.greaterThan( 1.0 ).discard();
  15991. } );
  15992. }
  15993. }
  15994. return alpha;
  15995. } )();
  15996. /**
  15997. * This node material can be used to render lines with a size larger than one
  15998. * by representing them as instanced meshes.
  15999. *
  16000. * @augments NodeMaterial
  16001. */
  16002. class Line2NodeMaterial extends NodeMaterial {
  16003. static get type() {
  16004. return 'Line2NodeMaterial';
  16005. }
  16006. /**
  16007. * Constructs a new node material for wide line rendering.
  16008. *
  16009. * @param {Object} [parameters={}] - The configuration parameter.
  16010. */
  16011. constructor( parameters = {} ) {
  16012. super();
  16013. /**
  16014. * This flag can be used for type testing.
  16015. *
  16016. * @type {boolean}
  16017. * @readonly
  16018. * @default true
  16019. */
  16020. this.isLine2NodeMaterial = true;
  16021. this.setDefaultValues( _defaultValues$b );
  16022. /**
  16023. * Whether vertex colors should be used or not.
  16024. *
  16025. * @type {boolean}
  16026. * @default false
  16027. */
  16028. this.vertexColors = parameters.vertexColors;
  16029. /**
  16030. * The dash offset.
  16031. *
  16032. * @type {number}
  16033. * @default 0
  16034. */
  16035. this.dashOffset = 0;
  16036. /**
  16037. * Defines the offset.
  16038. *
  16039. * @type {?Node<float>}
  16040. * @default null
  16041. */
  16042. this.offsetNode = null;
  16043. /**
  16044. * Defines the dash scale.
  16045. *
  16046. * @type {?Node<float>}
  16047. * @default null
  16048. */
  16049. this.dashScaleNode = null;
  16050. /**
  16051. * Defines the dash size.
  16052. *
  16053. * @type {?Node<float>}
  16054. * @default null
  16055. */
  16056. this.dashSizeNode = null;
  16057. /**
  16058. * Defines the gap size.
  16059. *
  16060. * @type {?Node<float>}
  16061. * @default null
  16062. */
  16063. this.gapSizeNode = null;
  16064. /**
  16065. * Blending is set to `NoBlending` since transparency
  16066. * is not supported, yet.
  16067. *
  16068. * @type {number}
  16069. * @default 0
  16070. */
  16071. this.blending = NoBlending;
  16072. this._useDash = parameters.dashed;
  16073. this._useAlphaToCoverage = true;
  16074. this._useWorldUnits = false;
  16075. this.setValues( parameters );
  16076. }
  16077. /**
  16078. * Setups the diffuse color of the line material in the fragment stage.
  16079. * Overrides the base setup to incorporate line/dash rendering and blending.
  16080. *
  16081. * @param {NodeBuilder} builder - The current node builder.
  16082. */
  16083. setupDiffuseColor( builder ) {
  16084. super.setupDiffuseColor( builder );
  16085. diffuseColor.a.mulAssign( alphaLine );
  16086. if ( this.vertexColors === true && builder.geometry.hasAttribute( 'instanceColorStart' ) ) {
  16087. const instanceColorStart = attribute( 'instanceColorStart' );
  16088. const instanceColorEnd = attribute( 'instanceColorEnd' );
  16089. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  16090. diffuseColor.rgb.mulAssign( instanceColor );
  16091. }
  16092. if ( this.transparent ) {
  16093. diffuseColor.rgb.assign( diffuseColor.rgb.mul( diffuseColor.a ).add( viewportOpaqueMipTexture().rgb.mul( diffuseColor.a.oneMinus() ) ) );
  16094. }
  16095. }
  16096. /**
  16097. * Setups the position in clip space for the vertex stage of the fat line.
  16098. * Overrides the default model-view-projection to return the expanded fat line vertex coordinates.
  16099. *
  16100. * @param {NodeBuilder} builder - The current node builder.
  16101. * @return {Node<vec4>} The position of the fat line vertex in clip space.
  16102. */
  16103. setupModelViewProjection( /*builder*/ ) {
  16104. return mvpLine;
  16105. }
  16106. /**
  16107. * Defines the lines color.
  16108. *
  16109. * @deprecated since r185. Use {@link NodeMaterial#colorNode} instead.
  16110. * @type {?Node<vec3>}
  16111. */
  16112. get lineColorNode() {
  16113. return this.colorNode;
  16114. }
  16115. set lineColorNode( value ) {
  16116. warnOnce( 'Line2NodeMaterial: "lineColorNode" has been deprecated. Use "colorNode" instead.' ); // @deprecated r185
  16117. this.colorNode = value;
  16118. }
  16119. /**
  16120. * Whether the lines should sized in world units or not.
  16121. * When set to `false` the unit is pixel.
  16122. *
  16123. * @type {boolean}
  16124. * @default false
  16125. */
  16126. get worldUnits() {
  16127. return this._useWorldUnits;
  16128. }
  16129. set worldUnits( value ) {
  16130. if ( this._useWorldUnits !== value ) {
  16131. this._useWorldUnits = value;
  16132. this.needsUpdate = true;
  16133. }
  16134. }
  16135. /**
  16136. * Whether the lines should be dashed or not.
  16137. *
  16138. * @type {boolean}
  16139. * @default false
  16140. */
  16141. get dashed() {
  16142. return this._useDash;
  16143. }
  16144. set dashed( value ) {
  16145. if ( this._useDash !== value ) {
  16146. this._useDash = value;
  16147. this.needsUpdate = true;
  16148. }
  16149. }
  16150. /**
  16151. * Whether alpha to coverage should be used or not.
  16152. *
  16153. * @type {boolean}
  16154. * @default true
  16155. */
  16156. get alphaToCoverage() {
  16157. return this._useAlphaToCoverage;
  16158. }
  16159. set alphaToCoverage( value ) {
  16160. if ( this._useAlphaToCoverage !== value ) {
  16161. this._useAlphaToCoverage = value;
  16162. this.needsUpdate = true;
  16163. }
  16164. }
  16165. }
  16166. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  16167. /**
  16168. * Node material version of {@link MeshNormalMaterial}.
  16169. *
  16170. * @augments NodeMaterial
  16171. */
  16172. class MeshNormalNodeMaterial extends NodeMaterial {
  16173. static get type() {
  16174. return 'MeshNormalNodeMaterial';
  16175. }
  16176. /**
  16177. * Constructs a new mesh normal node material.
  16178. *
  16179. * @param {Object} [parameters] - The configuration parameter.
  16180. */
  16181. constructor( parameters ) {
  16182. super();
  16183. /**
  16184. * This flag can be used for type testing.
  16185. *
  16186. * @type {boolean}
  16187. * @readonly
  16188. * @default true
  16189. */
  16190. this.isMeshNormalNodeMaterial = true;
  16191. this.setDefaultValues( _defaultValues$a );
  16192. this.setValues( parameters );
  16193. }
  16194. /**
  16195. * Overwrites the default implementation by computing the diffuse color
  16196. * based on the normal data.
  16197. */
  16198. setupDiffuseColor() {
  16199. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  16200. // By convention, a normal packed to RGB is in sRGB color space. Convert it to working color space.
  16201. diffuseColor.assign( colorSpaceToWorking( vec4( packNormalToRGB( normalView ), opacityNode ), SRGBColorSpace ) );
  16202. }
  16203. }
  16204. /**
  16205. * TSL function for creating an equirect uv node.
  16206. *
  16207. * Can be used to compute texture coordinates for projecting an
  16208. * equirectangular texture onto a mesh for using it as the scene's
  16209. * background.
  16210. *
  16211. * ```js
  16212. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  16213. * ```
  16214. *
  16215. * @tsl
  16216. * @function
  16217. * @param {?Node<vec3>} [direction=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  16218. * @returns {Node<vec2>}
  16219. */
  16220. const equirectUV = /*@__PURE__*/ Fn( ( [ direction = positionWorldDirection ] ) => {
  16221. const u = direction.z.atan( direction.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  16222. const v = direction.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  16223. return vec2( u, v );
  16224. } );
  16225. /**
  16226. * TSL function for creating an equirect direction node.
  16227. *
  16228. * Can be used to compute a direction vector from the given equirectangular
  16229. * UV coordinates.
  16230. *
  16231. * @tsl
  16232. * @function
  16233. * @param {?Node<vec2>} [uv=UV()] - The equirectangular UV coordinates.
  16234. * @returns {Node<vec3>} The computed direction vector.
  16235. */
  16236. const equirectDirection = /*@__PURE__*/ Fn( ( [ uv = uv$1() ] ) => {
  16237. const theta = uv.x.sub( 0.5 ).mul( Math.PI * 2 );
  16238. const phi = uv.y.sub( 0.5 ).mul( Math.PI );
  16239. const cosPhi = phi.cos();
  16240. const x = cosPhi.mul( theta.cos() );
  16241. const y = phi.sin();
  16242. const z = cosPhi.mul( theta.sin() );
  16243. return vec3( x, y, z );
  16244. } );
  16245. /**
  16246. * This class represents a cube render target. It is a special version
  16247. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  16248. *
  16249. * @augments RenderTarget
  16250. */
  16251. class CubeRenderTarget extends RenderTarget {
  16252. /**
  16253. * Constructs a new cube render target.
  16254. *
  16255. * @param {number} [size=1] - The size of the render target.
  16256. * @param {RenderTarget~Options} [options] - The configuration object.
  16257. */
  16258. constructor( size = 1, options = {} ) {
  16259. super( size, size, options );
  16260. /**
  16261. * This flag can be used for type testing.
  16262. *
  16263. * @type {boolean}
  16264. * @readonly
  16265. * @default true
  16266. */
  16267. this.isCubeRenderTarget = true;
  16268. const image = { width: size, height: size, depth: 1 };
  16269. const images = [ image, image, image, image, image, image ];
  16270. /**
  16271. * Overwritten with a different texture type.
  16272. *
  16273. * @type {DataArrayTexture}
  16274. */
  16275. this.texture = new CubeTexture( images );
  16276. this._setTextureOptions( options );
  16277. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  16278. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  16279. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  16280. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  16281. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  16282. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  16283. this.texture.isRenderTargetTexture = true;
  16284. }
  16285. /**
  16286. * Converts the given equirectangular texture to a cube map.
  16287. *
  16288. * @param {Renderer} renderer - The renderer.
  16289. * @param {Texture} texture - The equirectangular texture.
  16290. * @return {CubeRenderTarget} A reference to this cube render target.
  16291. */
  16292. fromEquirectangularTexture( renderer, texture$1 ) {
  16293. const currentMinFilter = texture$1.minFilter;
  16294. const currentGenerateMipmaps = texture$1.generateMipmaps;
  16295. texture$1.generateMipmaps = true;
  16296. this.texture.type = texture$1.type;
  16297. this.texture.colorSpace = texture$1.colorSpace;
  16298. this.texture.generateMipmaps = texture$1.generateMipmaps;
  16299. this.texture.minFilter = texture$1.minFilter;
  16300. this.texture.magFilter = texture$1.magFilter;
  16301. const geometry = new BoxGeometry( 5, 5, 5 );
  16302. const uvNode = equirectUV( positionWorldDirection );
  16303. const material = new NodeMaterial();
  16304. material.colorNode = texture( texture$1, uvNode, 0 );
  16305. material.side = BackSide;
  16306. material.blending = NoBlending;
  16307. const mesh = new Mesh( geometry, material );
  16308. const scene = new Scene();
  16309. scene.add( mesh );
  16310. // Avoid blurred poles
  16311. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  16312. const camera = new CubeCamera( 1, 10, this );
  16313. const currentMRT = renderer.getMRT();
  16314. renderer.setMRT( null );
  16315. camera.update( renderer, scene );
  16316. renderer.setMRT( currentMRT );
  16317. texture$1.minFilter = currentMinFilter;
  16318. texture$1.generateMipmaps = currentGenerateMipmaps;
  16319. mesh.geometry.dispose();
  16320. mesh.material.dispose();
  16321. return this;
  16322. }
  16323. /**
  16324. * Clears this cube render target.
  16325. *
  16326. * @param {Renderer} renderer - The renderer.
  16327. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  16328. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  16329. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  16330. */
  16331. clear( renderer, color = true, depth = true, stencil = true ) {
  16332. const currentRenderTarget = renderer.getRenderTarget();
  16333. for ( let i = 0; i < 6; i ++ ) {
  16334. renderer.setRenderTarget( this, i );
  16335. renderer.clear( color, depth, stencil );
  16336. }
  16337. renderer.setRenderTarget( currentRenderTarget );
  16338. }
  16339. }
  16340. const _cache$1 = new WeakMap();
  16341. /**
  16342. * This node can be used to automatically convert environment maps in the
  16343. * equirectangular format into the cube map format.
  16344. *
  16345. * @augments TempNode
  16346. */
  16347. class CubeMapNode extends TempNode {
  16348. static get type() {
  16349. return 'CubeMapNode';
  16350. }
  16351. /**
  16352. * Constructs a new cube map node.
  16353. *
  16354. * @param {Node} envNode - The node representing the environment map.
  16355. */
  16356. constructor( envNode ) {
  16357. super( 'vec3' );
  16358. /**
  16359. * The node representing the environment map.
  16360. *
  16361. * @type {Node}
  16362. */
  16363. this.envNode = envNode;
  16364. /**
  16365. * A reference to the internal cube texture.
  16366. *
  16367. * @private
  16368. * @type {?CubeTexture}
  16369. * @default null
  16370. */
  16371. this._cubeTexture = null;
  16372. /**
  16373. * A reference to the internal cube texture node.
  16374. *
  16375. * @private
  16376. * @type {CubeTextureNode}
  16377. */
  16378. this._cubeTextureNode = cubeTexture( null );
  16379. const defaultTexture = new CubeTexture();
  16380. defaultTexture.isRenderTargetTexture = true;
  16381. /**
  16382. * A default cube texture that acts as a placeholder.
  16383. * It is used when the conversion from equirectangular to cube
  16384. * map has not finished yet for a given texture.
  16385. *
  16386. * @private
  16387. * @type {CubeTexture}
  16388. */
  16389. this._defaultTexture = defaultTexture;
  16390. /**
  16391. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  16392. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  16393. *
  16394. * @type {string}
  16395. * @default 'render'
  16396. */
  16397. this.updateBeforeType = NodeUpdateType.RENDER;
  16398. }
  16399. updateBefore( frame ) {
  16400. const { renderer, material } = frame;
  16401. const envNode = this.envNode;
  16402. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  16403. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  16404. if ( texture && texture.isTexture ) {
  16405. const mapping = texture.mapping;
  16406. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  16407. // check for converted cubemap map
  16408. if ( _cache$1.has( texture ) ) {
  16409. const cubeMap = _cache$1.get( texture );
  16410. mapTextureMapping( cubeMap, texture.mapping );
  16411. this._cubeTexture = cubeMap;
  16412. } else {
  16413. // create cube map from equirectangular map
  16414. const image = texture.image;
  16415. if ( isEquirectangularMapReady$1( image ) ) {
  16416. const renderTarget = new CubeRenderTarget( image.height );
  16417. renderTarget.fromEquirectangularTexture( renderer, texture );
  16418. mapTextureMapping( renderTarget.texture, texture.mapping );
  16419. this._cubeTexture = renderTarget.texture;
  16420. _cache$1.set( texture, renderTarget.texture );
  16421. texture.addEventListener( 'dispose', onTextureDispose );
  16422. } else {
  16423. // default cube texture as fallback when equirectangular texture is not yet loaded
  16424. this._cubeTexture = this._defaultTexture;
  16425. }
  16426. }
  16427. //
  16428. this._cubeTextureNode.value = this._cubeTexture;
  16429. } else {
  16430. // envNode already refers to a cube map
  16431. this._cubeTextureNode = this.envNode;
  16432. }
  16433. }
  16434. }
  16435. }
  16436. setup( builder ) {
  16437. this.updateBefore( builder );
  16438. return this._cubeTextureNode;
  16439. }
  16440. }
  16441. /**
  16442. * Returns true if the given equirectangular image has been fully loaded
  16443. * and is ready for further processing.
  16444. *
  16445. * @private
  16446. * @param {Image} image - The equirectangular image to check.
  16447. * @return {boolean} Whether the image is ready or not.
  16448. */
  16449. function isEquirectangularMapReady$1( image ) {
  16450. if ( image === null || image === undefined ) return false;
  16451. return image.height > 0;
  16452. }
  16453. /**
  16454. * This function is executed when `dispose()` is called on the equirectangular
  16455. * texture. In this case, the generated cube map with its render target
  16456. * is deleted as well.
  16457. *
  16458. * @private
  16459. * @param {Object} event - The event object.
  16460. */
  16461. function onTextureDispose( event ) {
  16462. const texture = event.target;
  16463. texture.removeEventListener( 'dispose', onTextureDispose );
  16464. const renderTarget = _cache$1.get( texture );
  16465. if ( renderTarget !== undefined ) {
  16466. _cache$1.delete( texture );
  16467. renderTarget.dispose();
  16468. }
  16469. }
  16470. /**
  16471. * This function makes sure the generated cube map uses the correct
  16472. * texture mapping that corresponds to the equirectangular original.
  16473. *
  16474. * @private
  16475. * @param {Texture} texture - The cube texture.
  16476. * @param {number} mapping - The original texture mapping.
  16477. */
  16478. function mapTextureMapping( texture, mapping ) {
  16479. if ( mapping === EquirectangularReflectionMapping ) {
  16480. texture.mapping = CubeReflectionMapping;
  16481. } else if ( mapping === EquirectangularRefractionMapping ) {
  16482. texture.mapping = CubeRefractionMapping;
  16483. }
  16484. }
  16485. /**
  16486. * TSL function for creating a cube map node.
  16487. *
  16488. * @tsl
  16489. * @function
  16490. * @param {Node} envNode - The node representing the environment map.
  16491. * @returns {CubeMapNode}
  16492. */
  16493. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode ).setParameterLength( 1 );
  16494. /**
  16495. * Represents a basic model for Image-based lighting (IBL). The environment
  16496. * is defined via environment maps in the equirectangular or cube map format.
  16497. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  16498. * or {@link MeshPhongNodeMaterial}.
  16499. *
  16500. * @augments LightingNode
  16501. */
  16502. class BasicEnvironmentNode extends LightingNode {
  16503. static get type() {
  16504. return 'BasicEnvironmentNode';
  16505. }
  16506. /**
  16507. * Constructs a new basic environment node.
  16508. *
  16509. * @param {Node} [envNode=null] - A node representing the environment.
  16510. */
  16511. constructor( envNode = null ) {
  16512. super();
  16513. /**
  16514. * A node representing the environment.
  16515. *
  16516. * @type {Node}
  16517. * @default null
  16518. */
  16519. this.envNode = envNode;
  16520. }
  16521. setup( builder ) {
  16522. // environment property is used in the finish() method of BasicLightingModel
  16523. builder.context.environment = cubeMapNode( this.envNode );
  16524. }
  16525. }
  16526. /**
  16527. * A specific version of {@link IrradianceNode} that is only relevant
  16528. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  16529. * requires a special scaling factor for the light map.
  16530. *
  16531. * @augments LightingNode
  16532. */
  16533. class BasicLightMapNode extends LightingNode {
  16534. static get type() {
  16535. return 'BasicLightMapNode';
  16536. }
  16537. /**
  16538. * Constructs a new basic light map node.
  16539. *
  16540. * @param {?Node<vec3>} [lightMapNode=null] - The light map node.
  16541. */
  16542. constructor( lightMapNode = null ) {
  16543. super();
  16544. /**
  16545. * The light map node.
  16546. *
  16547. * @type {?Node<vec3>}
  16548. */
  16549. this.lightMapNode = lightMapNode;
  16550. }
  16551. setup( builder ) {
  16552. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  16553. const RECIPROCAL_PI = float( 1 / Math.PI );
  16554. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  16555. }
  16556. }
  16557. /**
  16558. * Abstract class for implementing lighting models. The module defines
  16559. * multiple methods that concrete lighting models can implement. These
  16560. * methods are executed at different points during the light evaluation
  16561. * process.
  16562. */
  16563. class LightingModel {
  16564. /**
  16565. * This method is intended for setting up lighting model and context data
  16566. * which are later used in the evaluation process.
  16567. *
  16568. * @abstract
  16569. * @param {NodeBuilder} builder - The current node builder.
  16570. */
  16571. start( builder ) {
  16572. // lights ( direct )
  16573. builder.lightsNode.setupLights( builder, builder.lightsNode.getLightNodes( builder ) );
  16574. // indirect
  16575. this.indirect( builder );
  16576. }
  16577. /**
  16578. * This method is intended for executing final tasks like final updates
  16579. * to the outgoing light.
  16580. *
  16581. * @abstract
  16582. * @param {NodeBuilder} builder - The current node builder.
  16583. */
  16584. finish( /*builder*/ ) { }
  16585. /**
  16586. * This method is intended for implementing the direct light term and
  16587. * executed during the build process of directional, point and spot light nodes.
  16588. *
  16589. * @abstract
  16590. * @param {Object} lightData - The light data.
  16591. * @param {NodeBuilder} builder - The current node builder.
  16592. */
  16593. direct( /*lightData, builder*/ ) { }
  16594. /**
  16595. * This method is intended for implementing the direct light term for
  16596. * rect area light nodes.
  16597. *
  16598. * @abstract
  16599. * @param {Object} lightData - The light data.
  16600. * @param {NodeBuilder} builder - The current node builder.
  16601. */
  16602. directRectArea( /*lightData, builder*/ ) {}
  16603. /**
  16604. * This method is intended for implementing the indirect light term.
  16605. *
  16606. * @abstract
  16607. * @param {NodeBuilder} builder - The current node builder.
  16608. */
  16609. indirect( /*builder*/ ) { }
  16610. /**
  16611. * This method is intended for implementing the ambient occlusion term.
  16612. * Unlike other methods, this method must be called manually by the lighting
  16613. * model in its indirect term.
  16614. *
  16615. * @abstract
  16616. * @param {NodeBuilder} builder - The current node builder.
  16617. */
  16618. ambientOcclusion( /*input, stack, builder*/ ) { }
  16619. }
  16620. /**
  16621. * Represents the lighting model for unlit materials. The only light contribution
  16622. * is baked indirect lighting modulated with ambient occlusion and the material's
  16623. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  16624. *
  16625. * @augments LightingModel
  16626. */
  16627. class BasicLightingModel extends LightingModel {
  16628. /**
  16629. * Constructs a new basic lighting model.
  16630. */
  16631. constructor() {
  16632. super();
  16633. }
  16634. /**
  16635. * Implements the baked indirect lighting with its modulation.
  16636. *
  16637. * @param {NodeBuilder} builder - The current node builder.
  16638. */
  16639. indirect( { context } ) {
  16640. const ambientOcclusion = context.ambientOcclusion;
  16641. const reflectedLight = context.reflectedLight;
  16642. const irradianceLightMap = context.irradianceLightMap;
  16643. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  16644. // accumulation (baked indirect lighting only)
  16645. if ( irradianceLightMap ) {
  16646. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  16647. } else {
  16648. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  16649. }
  16650. // modulation
  16651. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16652. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  16653. }
  16654. /**
  16655. * Implements the environment mapping.
  16656. *
  16657. * @param {NodeBuilder} builder - The current node builder.
  16658. */
  16659. finish( builder ) {
  16660. const { material, context } = builder;
  16661. const outgoingLight = context.outgoingLight;
  16662. const envNode = builder.context.environment;
  16663. if ( envNode ) {
  16664. switch ( material.combine ) {
  16665. case MultiplyOperation:
  16666. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  16667. break;
  16668. case MixOperation:
  16669. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  16670. break;
  16671. case AddOperation:
  16672. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  16673. break;
  16674. default:
  16675. warn( 'BasicLightingModel: Unsupported .combine value:', material.combine );
  16676. break;
  16677. }
  16678. }
  16679. }
  16680. }
  16681. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  16682. /**
  16683. * Node material version of {@link MeshBasicMaterial}.
  16684. *
  16685. * @augments NodeMaterial
  16686. */
  16687. class MeshBasicNodeMaterial extends NodeMaterial {
  16688. static get type() {
  16689. return 'MeshBasicNodeMaterial';
  16690. }
  16691. /**
  16692. * Constructs a new mesh basic node material.
  16693. *
  16694. * @param {Object} [parameters] - The configuration parameter.
  16695. */
  16696. constructor( parameters ) {
  16697. super();
  16698. /**
  16699. * This flag can be used for type testing.
  16700. *
  16701. * @type {boolean}
  16702. * @readonly
  16703. * @default true
  16704. */
  16705. this.isMeshBasicNodeMaterial = true;
  16706. /**
  16707. * Although the basic material is by definition unlit, we set
  16708. * this property to `true` since we use a lighting model to compute
  16709. * the outgoing light of the fragment shader.
  16710. *
  16711. * @type {boolean}
  16712. * @default true
  16713. */
  16714. this.lights = true;
  16715. this.setDefaultValues( _defaultValues$9 );
  16716. this.setValues( parameters );
  16717. }
  16718. /**
  16719. * Basic materials are not affected by normal and bump maps so we
  16720. * return by default {@link normalViewGeometry}.
  16721. *
  16722. * @return {Node<vec3>} The normal node.
  16723. */
  16724. setupNormal() {
  16725. return negateOnBackSide( normalViewGeometry ); // see #28839
  16726. }
  16727. /**
  16728. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16729. * to implement the default environment mapping.
  16730. *
  16731. * @param {NodeBuilder} builder - The current node builder.
  16732. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16733. */
  16734. setupEnvironment( builder ) {
  16735. const envNode = super.setupEnvironment( builder );
  16736. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16737. }
  16738. /**
  16739. * This method must be overwritten since light maps are evaluated
  16740. * with a special scaling factor for basic materials.
  16741. *
  16742. * @param {NodeBuilder} builder - The current node builder.
  16743. * @return {?BasicLightMapNode<vec3>} The light map node.
  16744. */
  16745. setupLightMap( builder ) {
  16746. let node = null;
  16747. if ( builder.material.lightMap ) {
  16748. node = new BasicLightMapNode( materialLightMap );
  16749. }
  16750. return node;
  16751. }
  16752. /**
  16753. * The material overwrites this method because `lights` is set to `true` but
  16754. * we still want to return the diffuse color as the outgoing light.
  16755. *
  16756. * @return {Node<vec3>} The outgoing light node.
  16757. */
  16758. setupOutgoingLight() {
  16759. return diffuseColor.rgb;
  16760. }
  16761. /**
  16762. * Setups the lighting model.
  16763. *
  16764. * @return {BasicLightingModel} The lighting model.
  16765. */
  16766. setupLightingModel() {
  16767. return new BasicLightingModel();
  16768. }
  16769. }
  16770. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  16771. // Original approximation by Christophe Schlick '94
  16772. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  16773. // Optimized variant (presented by Epic at SIGGRAPH '13)
  16774. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  16775. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  16776. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  16777. } ); // validated
  16778. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  16779. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  16780. } ); // validated
  16781. const G_BlinnPhong_Implicit = () => float( 0.25 );
  16782. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  16783. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  16784. } );
  16785. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  16786. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16787. const dotNH = normalView.dot( halfDir ).clamp();
  16788. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  16789. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  16790. const G = G_BlinnPhong_Implicit();
  16791. const D = D_BlinnPhong( { dotNH } );
  16792. return F.mul( G ).mul( D );
  16793. } );
  16794. /**
  16795. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  16796. *
  16797. * @augments BasicLightingModel
  16798. */
  16799. class PhongLightingModel extends BasicLightingModel {
  16800. /**
  16801. * Constructs a new phong lighting model.
  16802. *
  16803. * @param {boolean} [specular=true] - Whether specular is supported or not.
  16804. */
  16805. constructor( specular = true ) {
  16806. super();
  16807. /**
  16808. * Whether specular is supported or not. Set this to `false` if you are
  16809. * looking for a Lambert-like material meaning a material for non-shiny
  16810. * surfaces, without specular highlights.
  16811. *
  16812. * @type {boolean}
  16813. * @default true
  16814. */
  16815. this.specular = specular;
  16816. }
  16817. /**
  16818. * Implements the direct lighting. The specular portion is optional an can be controlled
  16819. * with the {@link PhongLightingModel#specular} flag.
  16820. *
  16821. * @param {Object} lightData - The light data.
  16822. */
  16823. direct( { lightDirection, lightColor, reflectedLight } ) {
  16824. const dotNL = normalView.dot( lightDirection ).clamp();
  16825. const irradiance = dotNL.mul( lightColor );
  16826. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  16827. if ( this.specular === true ) {
  16828. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  16829. }
  16830. }
  16831. /**
  16832. * Implements the indirect lighting.
  16833. *
  16834. * @param {NodeBuilder} builder - The current node builder.
  16835. */
  16836. indirect( builder ) {
  16837. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  16838. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  16839. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16840. }
  16841. }
  16842. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  16843. /**
  16844. * Node material version of {@link MeshLambertMaterial}.
  16845. *
  16846. * @augments NodeMaterial
  16847. */
  16848. class MeshLambertNodeMaterial extends NodeMaterial {
  16849. static get type() {
  16850. return 'MeshLambertNodeMaterial';
  16851. }
  16852. /**
  16853. * Constructs a new mesh lambert node material.
  16854. *
  16855. * @param {Object} [parameters] - The configuration parameter.
  16856. */
  16857. constructor( parameters ) {
  16858. super();
  16859. /**
  16860. * This flag can be used for type testing.
  16861. *
  16862. * @type {boolean}
  16863. * @readonly
  16864. * @default true
  16865. */
  16866. this.isMeshLambertNodeMaterial = true;
  16867. /**
  16868. * Set to `true` because lambert materials react on lights.
  16869. *
  16870. * @type {boolean}
  16871. * @default true
  16872. */
  16873. this.lights = true;
  16874. this.setDefaultValues( _defaultValues$8 );
  16875. this.setValues( parameters );
  16876. }
  16877. /**
  16878. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16879. * to implement the default environment mapping.
  16880. *
  16881. * @param {NodeBuilder} builder - The current node builder.
  16882. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16883. */
  16884. setupEnvironment( builder ) {
  16885. const envNode = super.setupEnvironment( builder );
  16886. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16887. }
  16888. /**
  16889. * Setups the lighting model.
  16890. *
  16891. * @return {PhongLightingModel} The lighting model.
  16892. */
  16893. setupLightingModel( /*builder*/ ) {
  16894. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  16895. }
  16896. }
  16897. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  16898. /**
  16899. * Node material version of {@link MeshPhongMaterial}.
  16900. *
  16901. * @augments NodeMaterial
  16902. */
  16903. class MeshPhongNodeMaterial extends NodeMaterial {
  16904. static get type() {
  16905. return 'MeshPhongNodeMaterial';
  16906. }
  16907. /**
  16908. * Constructs a new mesh lambert node material.
  16909. *
  16910. * @param {Object} [parameters] - The configuration parameter.
  16911. */
  16912. constructor( parameters ) {
  16913. super();
  16914. /**
  16915. * This flag can be used for type testing.
  16916. *
  16917. * @type {boolean}
  16918. * @readonly
  16919. * @default true
  16920. */
  16921. this.isMeshPhongNodeMaterial = true;
  16922. /**
  16923. * Set to `true` because phong materials react on lights.
  16924. *
  16925. * @type {boolean}
  16926. * @default true
  16927. */
  16928. this.lights = true;
  16929. /**
  16930. * The shininess of phong materials is by default inferred from the `shininess`
  16931. * property. This node property allows to overwrite the default
  16932. * and define the shininess with a node instead.
  16933. *
  16934. * If you don't want to overwrite the shininess but modify the existing
  16935. * value instead, use {@link materialShininess}.
  16936. *
  16937. * @type {?Node<float>}
  16938. * @default null
  16939. */
  16940. this.shininessNode = null;
  16941. /**
  16942. * The specular color of phong materials is by default inferred from the
  16943. * `specular` property. This node property allows to overwrite the default
  16944. * and define the specular color with a node instead.
  16945. *
  16946. * If you don't want to overwrite the specular color but modify the existing
  16947. * value instead, use {@link materialSpecular}.
  16948. *
  16949. * @type {?Node<vec3>}
  16950. * @default null
  16951. */
  16952. this.specularNode = null;
  16953. this.setDefaultValues( _defaultValues$7 );
  16954. this.setValues( parameters );
  16955. }
  16956. /**
  16957. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16958. * to implement the default environment mapping.
  16959. *
  16960. * @param {NodeBuilder} builder - The current node builder.
  16961. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16962. */
  16963. setupEnvironment( builder ) {
  16964. const envNode = super.setupEnvironment( builder );
  16965. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16966. }
  16967. /**
  16968. * Setups the lighting model.
  16969. *
  16970. * @return {PhongLightingModel} The lighting model.
  16971. */
  16972. setupLightingModel( /*builder*/ ) {
  16973. return new PhongLightingModel();
  16974. }
  16975. /**
  16976. * Setups the phong specific node variables.
  16977. *
  16978. * @param {NodeBuilder} builder - The current node builder.
  16979. */
  16980. setupVariants( /*builder*/ ) {
  16981. // SHININESS
  16982. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  16983. shininess.assign( shininessNode );
  16984. // SPECULAR COLOR
  16985. const specularNode = this.specularNode || materialSpecular;
  16986. specularColor.assign( specularNode );
  16987. }
  16988. }
  16989. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  16990. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  16991. return float( 0 );
  16992. }
  16993. const dxy = normalViewGeometry.dFdx().abs().max( normalViewGeometry.dFdy().abs() );
  16994. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  16995. return geometryRoughness;
  16996. } );
  16997. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  16998. const { roughness } = inputs;
  16999. const geometryRoughness = getGeometryRoughness();
  17000. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  17001. roughnessFactor = roughnessFactor.add( geometryRoughness );
  17002. roughnessFactor = roughnessFactor.min( 1.0 );
  17003. return roughnessFactor;
  17004. } );
  17005. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  17006. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  17007. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  17008. const a2 = alpha.pow2();
  17009. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  17010. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  17011. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  17012. } ).setLayout( {
  17013. name: 'V_GGX_SmithCorrelated',
  17014. type: 'float',
  17015. inputs: [
  17016. { name: 'alpha', type: 'float' },
  17017. { name: 'dotNL', type: 'float' },
  17018. { name: 'dotNV', type: 'float' }
  17019. ]
  17020. } ); // validated
  17021. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  17022. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  17023. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  17024. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  17025. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  17026. } ).setLayout( {
  17027. name: 'V_GGX_SmithCorrelated_Anisotropic',
  17028. type: 'float',
  17029. inputs: [
  17030. { name: 'alphaT', type: 'float', qualifier: 'in' },
  17031. { name: 'alphaB', type: 'float', qualifier: 'in' },
  17032. { name: 'dotTV', type: 'float', qualifier: 'in' },
  17033. { name: 'dotBV', type: 'float', qualifier: 'in' },
  17034. { name: 'dotTL', type: 'float', qualifier: 'in' },
  17035. { name: 'dotBL', type: 'float', qualifier: 'in' },
  17036. { name: 'dotNV', type: 'float', qualifier: 'in' },
  17037. { name: 'dotNL', type: 'float', qualifier: 'in' }
  17038. ]
  17039. } );
  17040. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  17041. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  17042. // alpha is "roughness squared" in Disney’s reparameterization
  17043. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  17044. const a2 = alpha.pow2();
  17045. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  17046. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  17047. } ).setLayout( {
  17048. name: 'D_GGX',
  17049. type: 'float',
  17050. inputs: [
  17051. { name: 'alpha', type: 'float' },
  17052. { name: 'dotNH', type: 'float' }
  17053. ]
  17054. } ); // validated
  17055. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  17056. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  17057. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  17058. const a2 = alphaT.mul( alphaB );
  17059. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  17060. const v2 = v.dot( v );
  17061. const w2 = a2.div( v2 );
  17062. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  17063. } ).setLayout( {
  17064. name: 'D_GGX_Anisotropic',
  17065. type: 'float',
  17066. inputs: [
  17067. { name: 'alphaT', type: 'float', qualifier: 'in' },
  17068. { name: 'alphaB', type: 'float', qualifier: 'in' },
  17069. { name: 'dotNH', type: 'float', qualifier: 'in' },
  17070. { name: 'dotTH', type: 'float', qualifier: 'in' },
  17071. { name: 'dotBH', type: 'float', qualifier: 'in' }
  17072. ]
  17073. } );
  17074. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  17075. const BRDF_GGX = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness, f, normalView: normalView$1 = normalView, viewDirection = positionViewDirection, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  17076. const alpha = roughness.pow2(); // UE4's roughness
  17077. const halfDir = lightDirection.add( viewDirection ).normalize();
  17078. const dotNL = normalView$1.dot( lightDirection ).clamp();
  17079. const dotNV = normalView$1.dot( viewDirection ).clamp(); // @ TODO: Move to core dotNV
  17080. const dotNH = normalView$1.dot( halfDir ).clamp();
  17081. const dotVH = viewDirection.dot( halfDir ).clamp();
  17082. let F = F_Schlick( { f0, f90, dotVH } );
  17083. let V, D;
  17084. if ( defined( USE_IRIDESCENCE ) ) {
  17085. F = iridescence.mix( F, f );
  17086. }
  17087. if ( defined( USE_ANISOTROPY ) ) {
  17088. const dotTL = anisotropyT.dot( lightDirection );
  17089. const dotTV = anisotropyT.dot( viewDirection );
  17090. const dotTH = anisotropyT.dot( halfDir );
  17091. const dotBL = anisotropyB.dot( lightDirection );
  17092. const dotBV = anisotropyB.dot( viewDirection );
  17093. const dotBH = anisotropyB.dot( halfDir );
  17094. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  17095. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  17096. } else {
  17097. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  17098. D = D_GGX( { alpha, dotNH } );
  17099. }
  17100. return F.mul( V ).mul( D );
  17101. } ); // validated
  17102. /**
  17103. * Precomputed DFG LUT for physically based specular lighting, used by both
  17104. * image-based lighting and direct-light multi-scattering energy compensation
  17105. * Resolution: 16x16
  17106. * Samples: 4096 per texel
  17107. * Format: RG16F (2 half floats per texel: scale, bias)
  17108. */
  17109. const DATA = new Uint16Array( [
  17110. 0x30b5, 0x3ad1, 0x314c, 0x3a4d, 0x33d2, 0x391c, 0x35ef, 0x3828, 0x37f3, 0x36a6, 0x38d1, 0x3539, 0x3979, 0x3410, 0x39f8, 0x3252, 0x3a53, 0x30f0, 0x3a94, 0x2fc9, 0x3abf, 0x2e35, 0x3ada, 0x2d05, 0x3ae8, 0x2c1f, 0x3aed, 0x2ae0, 0x3aea, 0x29d1, 0x3ae1, 0x28ff,
  17111. 0x3638, 0x38e4, 0x364a, 0x38ce, 0x3699, 0x385e, 0x374e, 0x372c, 0x3839, 0x35a4, 0x38dc, 0x3462, 0x396e, 0x32c4, 0x39de, 0x3134, 0x3a2b, 0x3003, 0x3a59, 0x2e3a, 0x3a6d, 0x2ce1, 0x3a6e, 0x2bba, 0x3a5f, 0x2a33, 0x3a49, 0x290a, 0x3a2d, 0x2826, 0x3a0a, 0x26e8,
  17112. 0x3894, 0x36d7, 0x3897, 0x36c9, 0x38a3, 0x3675, 0x38bc, 0x35ac, 0x38ee, 0x349c, 0x393e, 0x3332, 0x3997, 0x3186, 0x39e2, 0x3038, 0x3a13, 0x2e75, 0x3a29, 0x2cf5, 0x3a2d, 0x2bac, 0x3a21, 0x29ff, 0x3a04, 0x28bc, 0x39dc, 0x2790, 0x39ad, 0x261a, 0x3978, 0x24fa,
  17113. 0x39ac, 0x34a8, 0x39ac, 0x34a3, 0x39ae, 0x3480, 0x39ae, 0x3423, 0x39b1, 0x330e, 0x39c2, 0x31a9, 0x39e0, 0x3063, 0x39fc, 0x2eb5, 0x3a0c, 0x2d1d, 0x3a14, 0x2bcf, 0x3a07, 0x29ff, 0x39e9, 0x28a3, 0x39be, 0x273c, 0x3989, 0x25b3, 0x394a, 0x2488, 0x3907, 0x2345,
  17114. 0x3a77, 0x3223, 0x3a76, 0x321f, 0x3a73, 0x3204, 0x3a6a, 0x31b3, 0x3a58, 0x3114, 0x3a45, 0x303b, 0x3a34, 0x2eb6, 0x3a26, 0x2d31, 0x3a1e, 0x2bef, 0x3a0b, 0x2a0d, 0x39ec, 0x28a1, 0x39c0, 0x271b, 0x3987, 0x2580, 0x3944, 0x2449, 0x38fa, 0x22bd, 0x38ac, 0x2155,
  17115. 0x3b07, 0x2fca, 0x3b06, 0x2fca, 0x3b00, 0x2fb8, 0x3af4, 0x2f7c, 0x3adb, 0x2eea, 0x3ab4, 0x2e00, 0x3a85, 0x2cec, 0x3a5e, 0x2bc5, 0x3a36, 0x2a00, 0x3a0d, 0x2899, 0x39dc, 0x2707, 0x39a0, 0x2562, 0x395a, 0x2424, 0x390b, 0x2268, 0x38b7, 0x20fd, 0x385f, 0x1fd1,
  17116. 0x3b69, 0x2cb9, 0x3b68, 0x2cbb, 0x3b62, 0x2cbb, 0x3b56, 0x2cae, 0x3b3b, 0x2c78, 0x3b0d, 0x2c0a, 0x3acf, 0x2ae3, 0x3a92, 0x2998, 0x3a54, 0x2867, 0x3a17, 0x26d0, 0x39d3, 0x253c, 0x3989, 0x2402, 0x3935, 0x2226, 0x38dc, 0x20bd, 0x387d, 0x1f54, 0x381d, 0x1db3,
  17117. 0x3ba9, 0x296b, 0x3ba8, 0x296f, 0x3ba3, 0x297b, 0x3b98, 0x2987, 0x3b7f, 0x2976, 0x3b4e, 0x2927, 0x3b0e, 0x2895, 0x3ac2, 0x27b7, 0x3a73, 0x263b, 0x3a23, 0x24e7, 0x39d0, 0x239b, 0x3976, 0x21d9, 0x3917, 0x207e, 0x38b2, 0x1ee7, 0x384b, 0x1d53, 0x37c7, 0x1c1e,
  17118. 0x3bd2, 0x25cb, 0x3bd1, 0x25d3, 0x3bcd, 0x25f0, 0x3bc2, 0x261f, 0x3bad, 0x2645, 0x3b7d, 0x262d, 0x3b3e, 0x25c4, 0x3aec, 0x250f, 0x3a93, 0x243a, 0x3a32, 0x22ce, 0x39d0, 0x215b, 0x3969, 0x202a, 0x38fe, 0x1e6e, 0x388f, 0x1cf1, 0x381f, 0x1b9b, 0x3762, 0x19dd,
  17119. 0x3be9, 0x21ab, 0x3be9, 0x21b7, 0x3be5, 0x21e5, 0x3bdd, 0x2241, 0x3bc9, 0x22a7, 0x3ba0, 0x22ec, 0x3b62, 0x22cd, 0x3b0f, 0x2247, 0x3aae, 0x2175, 0x3a44, 0x2088, 0x39d4, 0x1f49, 0x3960, 0x1dbe, 0x38e9, 0x1c77, 0x3870, 0x1ae8, 0x37f1, 0x1953, 0x3708, 0x181b,
  17120. 0x3bf6, 0x1cea, 0x3bf6, 0x1cfb, 0x3bf3, 0x1d38, 0x3bec, 0x1dbd, 0x3bda, 0x1e7c, 0x3bb7, 0x1f25, 0x3b7d, 0x1f79, 0x3b2c, 0x1f4c, 0x3ac6, 0x1ea6, 0x3a55, 0x1dbb, 0x39da, 0x1cbd, 0x395a, 0x1b9d, 0x38d8, 0x1a00, 0x3855, 0x18ac, 0x37ab, 0x173c, 0x36b7, 0x1598,
  17121. 0x3bfc, 0x1736, 0x3bfc, 0x1759, 0x3bf9, 0x17e7, 0x3bf4, 0x1896, 0x3be4, 0x1997, 0x3bc6, 0x1aa8, 0x3b91, 0x1b84, 0x3b43, 0x1bd2, 0x3ade, 0x1b8a, 0x3a65, 0x1acd, 0x39e2, 0x19d3, 0x3957, 0x18cd, 0x38ca, 0x17b3, 0x383e, 0x1613, 0x376d, 0x14bf, 0x366f, 0x135e,
  17122. 0x3bff, 0x101b, 0x3bff, 0x1039, 0x3bfc, 0x10c8, 0x3bf9, 0x1226, 0x3bea, 0x1428, 0x3bcf, 0x1584, 0x3b9f, 0x16c5, 0x3b54, 0x179a, 0x3af0, 0x17ce, 0x3a76, 0x1771, 0x39ea, 0x16a4, 0x3956, 0x15a7, 0x38bf, 0x14a7, 0x3829, 0x1379, 0x3735, 0x11ea, 0x362d, 0x10a1,
  17123. 0x3c00, 0x061b, 0x3c00, 0x066a, 0x3bfe, 0x081c, 0x3bfa, 0x0a4c, 0x3bed, 0x0d16, 0x3bd5, 0x0fb3, 0x3ba9, 0x114d, 0x3b63, 0x127c, 0x3b01, 0x132f, 0x3a85, 0x1344, 0x39f4, 0x12d2, 0x3957, 0x120d, 0x38b5, 0x1122, 0x3817, 0x103c, 0x3703, 0x0ed3, 0x35f0, 0x0d6d,
  17124. 0x3c00, 0x007a, 0x3c00, 0x0089, 0x3bfe, 0x011d, 0x3bfb, 0x027c, 0x3bf0, 0x04fa, 0x3bda, 0x0881, 0x3bb1, 0x0acd, 0x3b6f, 0x0c97, 0x3b10, 0x0d7b, 0x3a93, 0x0df1, 0x39fe, 0x0def, 0x3959, 0x0d8a, 0x38af, 0x0ce9, 0x3808, 0x0c31, 0x36d5, 0x0af0, 0x35b9, 0x09a3,
  17125. 0x3c00, 0x0000, 0x3c00, 0x0001, 0x3bff, 0x0015, 0x3bfb, 0x0059, 0x3bf2, 0x00fd, 0x3bdd, 0x01df, 0x3bb7, 0x031c, 0x3b79, 0x047c, 0x3b1d, 0x05d4, 0x3aa0, 0x06d5, 0x3a08, 0x075a, 0x395d, 0x075e, 0x38aa, 0x06f7, 0x37f4, 0x0648, 0x36ac, 0x0576, 0x3586, 0x049f
  17126. ] );
  17127. let lut = null;
  17128. const DFGLUT = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  17129. if ( lut === null ) {
  17130. lut = new DataTexture( DATA, 16, 16, RGFormat, HalfFloatType );
  17131. lut.name = 'DFG_LUT';
  17132. lut.minFilter = LinearFilter;
  17133. lut.magFilter = LinearFilter;
  17134. lut.wrapS = ClampToEdgeWrapping;
  17135. lut.wrapT = ClampToEdgeWrapping;
  17136. lut.generateMipmaps = false;
  17137. lut.needsUpdate = true;
  17138. }
  17139. const uv = vec2( roughness, dotNV );
  17140. return texture( lut, uv ).rg;
  17141. } );
  17142. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  17143. const { dotNV, specularColor, specularF90, roughness } = inputs;
  17144. const fab = DFGLUT( { dotNV, roughness } );
  17145. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  17146. } );
  17147. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  17148. const x = dotVH.oneMinus().saturate();
  17149. const x2 = x.mul( x );
  17150. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  17151. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  17152. } ).setLayout( {
  17153. name: 'Schlick_to_F0',
  17154. type: 'vec3',
  17155. inputs: [
  17156. { name: 'f', type: 'vec3' },
  17157. { name: 'f90', type: 'float' },
  17158. { name: 'dotVH', type: 'float' }
  17159. ]
  17160. } );
  17161. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  17162. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  17163. const alpha = roughness.pow2();
  17164. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  17165. const invAlpha = float( 1.0 ).div( alpha );
  17166. const cos2h = dotNH.pow2();
  17167. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  17168. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  17169. } ).setLayout( {
  17170. name: 'D_Charlie',
  17171. type: 'float',
  17172. inputs: [
  17173. { name: 'roughness', type: 'float' },
  17174. { name: 'dotNH', type: 'float' }
  17175. ]
  17176. } );
  17177. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  17178. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  17179. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  17180. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  17181. } ).setLayout( {
  17182. name: 'V_Neubelt',
  17183. type: 'float',
  17184. inputs: [
  17185. { name: 'dotNV', type: 'float' },
  17186. { name: 'dotNL', type: 'float' }
  17187. ]
  17188. } );
  17189. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  17190. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  17191. const dotNL = normalView.dot( lightDirection ).clamp();
  17192. const dotNV = normalView.dot( positionViewDirection ).clamp();
  17193. const dotNH = normalView.dot( halfDir ).clamp();
  17194. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  17195. const V = V_Neubelt( { dotNV, dotNL } );
  17196. return sheen.mul( D ).mul( V );
  17197. } );
  17198. // Rect Area Light
  17199. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  17200. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  17201. // code: https://github.com/selfshadow/ltc_code/
  17202. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  17203. const LUT_SIZE = 64.0;
  17204. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  17205. const LUT_BIAS = 0.5 / LUT_SIZE;
  17206. const dotNV = N.dot( V ).saturate();
  17207. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  17208. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  17209. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  17210. return uv;
  17211. } ).setLayout( {
  17212. name: 'LTC_Uv',
  17213. type: 'vec2',
  17214. inputs: [
  17215. { name: 'N', type: 'vec3' },
  17216. { name: 'V', type: 'vec3' },
  17217. { name: 'roughness', type: 'float' }
  17218. ]
  17219. } );
  17220. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  17221. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  17222. // An approximation of the form factor of a horizon-clipped rectangle.
  17223. const l = f.length();
  17224. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  17225. } ).setLayout( {
  17226. name: 'LTC_ClippedSphereFormFactor',
  17227. type: 'float',
  17228. inputs: [
  17229. { name: 'f', type: 'vec3' }
  17230. ]
  17231. } );
  17232. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  17233. const x = v1.dot( v2 );
  17234. const y = x.abs().toVar();
  17235. // rational polynomial approximation to theta / sin( theta ) / 2PI
  17236. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  17237. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  17238. const v = a.div( b );
  17239. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  17240. return v1.cross( v2 ).mul( theta_sintheta );
  17241. } ).setLayout( {
  17242. name: 'LTC_EdgeVectorFormFactor',
  17243. type: 'vec3',
  17244. inputs: [
  17245. { name: 'v1', type: 'vec3' },
  17246. { name: 'v2', type: 'vec3' }
  17247. ]
  17248. } );
  17249. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  17250. // bail if point is on back side of plane of light
  17251. // assumes ccw winding order of light vertices
  17252. const v1 = p1.sub( p0 ).toVar();
  17253. const v2 = p3.sub( p0 ).toVar();
  17254. const lightNormal = v1.cross( v2 );
  17255. const result = vec3().toVar();
  17256. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  17257. // construct orthonormal basis around N
  17258. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  17259. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  17260. // compute transform
  17261. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  17262. // transform rect
  17263. // & project rect onto sphere
  17264. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  17265. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  17266. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  17267. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  17268. // calculate vector form factor
  17269. const vectorFormFactor = vec3( 0 ).toVar();
  17270. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  17271. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  17272. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  17273. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  17274. // adjust for horizon clipping
  17275. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  17276. } );
  17277. return result;
  17278. } ).setLayout( {
  17279. name: 'LTC_Evaluate',
  17280. type: 'vec3',
  17281. inputs: [
  17282. { name: 'N', type: 'vec3' },
  17283. { name: 'V', type: 'vec3' },
  17284. { name: 'P', type: 'vec3' },
  17285. { name: 'mInv', type: 'mat3' },
  17286. { name: 'p0', type: 'vec3' },
  17287. { name: 'p1', type: 'vec3' },
  17288. { name: 'p2', type: 'vec3' },
  17289. { name: 'p3', type: 'vec3' }
  17290. ]
  17291. } );
  17292. const LTC_Evaluate_Volume = /*@__PURE__*/ Fn( ( { P, p0, p1, p2, p3 } ) => {
  17293. // bail if point is on back side of plane of light
  17294. // assumes ccw winding order of light vertices
  17295. const v1 = p1.sub( p0 ).toVar();
  17296. const v2 = p3.sub( p0 ).toVar();
  17297. const lightNormal = v1.cross( v2 );
  17298. const result = vec3().toVar();
  17299. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  17300. // transform rect
  17301. // & project rect onto sphere
  17302. const coords0 = p0.sub( P ).normalize().toVar();
  17303. const coords1 = p1.sub( P ).normalize().toVar();
  17304. const coords2 = p2.sub( P ).normalize().toVar();
  17305. const coords3 = p3.sub( P ).normalize().toVar();
  17306. // calculate vector form factor
  17307. const vectorFormFactor = vec3( 0 ).toVar();
  17308. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  17309. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  17310. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  17311. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  17312. // adjust for horizon clipping
  17313. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor.abs() } ) ) );
  17314. } );
  17315. return result;
  17316. } ).setLayout( {
  17317. name: 'LTC_Evaluate',
  17318. type: 'vec3',
  17319. inputs: [
  17320. { name: 'P', type: 'vec3' },
  17321. { name: 'p0', type: 'vec3' },
  17322. { name: 'p1', type: 'vec3' },
  17323. { name: 'p2', type: 'vec3' },
  17324. { name: 'p3', type: 'vec3' }
  17325. ]
  17326. } );
  17327. // Mipped Bicubic Texture Filtering by N8
  17328. // https://www.shadertoy.com/view/Dl2SDW
  17329. const bC = 1.0 / 6.0;
  17330. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  17331. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  17332. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  17333. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  17334. const g0 = ( a ) => w0( a ).add( w1( a ) );
  17335. const g1 = ( a ) => w2( a ).add( w3( a ) );
  17336. // h0 and h1 are the two offset functions
  17337. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  17338. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  17339. const bicubic = ( textureNode, texelSize, lod ) => {
  17340. const uv = textureNode.uvNode;
  17341. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  17342. const iuv = floor( uvScaled );
  17343. const fuv = fract( uvScaled );
  17344. const g0x = g0( fuv.x );
  17345. const g1x = g1( fuv.x );
  17346. const h0x = h0( fuv.x );
  17347. const h1x = h1( fuv.x );
  17348. const h0y = h0( fuv.y );
  17349. const h1y = h1( fuv.y );
  17350. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  17351. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  17352. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  17353. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  17354. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  17355. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  17356. return a.add( b );
  17357. };
  17358. /**
  17359. * Applies mipped bicubic texture filtering to the given texture node.
  17360. *
  17361. * @tsl
  17362. * @function
  17363. * @param {TextureNode} textureNode - The texture node that should be filtered.
  17364. * @param {Node<float>} lodNode - Defines the LOD to sample from.
  17365. * @return {Node} The filtered texture sample.
  17366. */
  17367. const textureBicubicLevel = /*@__PURE__*/ Fn( ( [ textureNode, lodNode ] ) => {
  17368. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  17369. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  17370. const fLodSizeInv = div( 1.0, fLodSize );
  17371. const cLodSizeInv = div( 1.0, cLodSize );
  17372. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  17373. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  17374. return fract( lodNode ).mix( fSample, cSample );
  17375. } );
  17376. /**
  17377. * Applies mipped bicubic texture filtering to the given texture node.
  17378. *
  17379. * @tsl
  17380. * @function
  17381. * @param {TextureNode} textureNode - The texture node that should be filtered.
  17382. * @param {Node<float>} [strength] - Defines the strength of the bicubic filtering.
  17383. * @return {Node} The filtered texture sample.
  17384. */
  17385. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, strength ] ) => {
  17386. const lod = strength.mul( maxMipLevel( textureNode ) );
  17387. return textureBicubicLevel( textureNode, lod );
  17388. } );
  17389. //
  17390. // Transmission
  17391. //
  17392. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  17393. // Direction of refracted light.
  17394. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  17395. // Compute rotation-independent scaling of the model matrix.
  17396. const modelScale = vec3(
  17397. length( modelMatrix[ 0 ].xyz ),
  17398. length( modelMatrix[ 1 ].xyz ),
  17399. length( modelMatrix[ 2 ].xyz )
  17400. );
  17401. // The thickness is specified in local space.
  17402. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  17403. } ).setLayout( {
  17404. name: 'getVolumeTransmissionRay',
  17405. type: 'vec3',
  17406. inputs: [
  17407. { name: 'n', type: 'vec3' },
  17408. { name: 'v', type: 'vec3' },
  17409. { name: 'thickness', type: 'float' },
  17410. { name: 'ior', type: 'float' },
  17411. { name: 'modelMatrix', type: 'mat4' }
  17412. ]
  17413. } );
  17414. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  17415. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  17416. // an IOR of 1.5 results in the default amount of microfacet refraction.
  17417. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  17418. } ).setLayout( {
  17419. name: 'applyIorToRoughness',
  17420. type: 'float',
  17421. inputs: [
  17422. { name: 'roughness', type: 'float' },
  17423. { name: 'ior', type: 'float' }
  17424. ]
  17425. } );
  17426. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  17427. const viewportFrontSideTexture = /*@__PURE__*/ viewportOpaqueMipTexture();
  17428. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  17429. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  17430. const transmissionSample = vTexture.sample( fragCoord );
  17431. //const transmissionSample = viewportMipTexture( fragCoord );
  17432. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  17433. return textureBicubicLevel( transmissionSample, lod );
  17434. } );
  17435. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  17436. If( attenuationDistance.notEqual( 0 ), () => {
  17437. // Compute light attenuation using Beer's law.
  17438. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  17439. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  17440. return transmittance;
  17441. } );
  17442. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  17443. return vec3( 1.0 );
  17444. } ).setLayout( {
  17445. name: 'volumeAttenuation',
  17446. type: 'vec3',
  17447. inputs: [
  17448. { name: 'transmissionDistance', type: 'float' },
  17449. { name: 'attenuationColor', type: 'vec3' },
  17450. { name: 'attenuationDistance', type: 'float' }
  17451. ]
  17452. } );
  17453. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  17454. let transmittedLight, transmittance;
  17455. if ( dispersion ) {
  17456. transmittedLight = vec4().toVar();
  17457. transmittance = vec3().toVar();
  17458. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  17459. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  17460. Loop( { start: 0, end: 3 }, ( { i } ) => {
  17461. const ior = iors.element( i );
  17462. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  17463. const refractedRayExit = position.add( transmissionRay );
  17464. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  17465. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  17466. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  17467. refractionCoords.addAssign( 1.0 );
  17468. refractionCoords.divAssign( 2.0 );
  17469. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  17470. // Sample framebuffer to get pixel the refracted ray hits.
  17471. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  17472. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  17473. transmittedLight.a.addAssign( transmissionSample.a );
  17474. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  17475. } );
  17476. transmittedLight.a.divAssign( 3.0 );
  17477. } else {
  17478. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  17479. const refractedRayExit = position.add( transmissionRay );
  17480. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  17481. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  17482. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  17483. refractionCoords.addAssign( 1.0 );
  17484. refractionCoords.divAssign( 2.0 );
  17485. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  17486. // Sample framebuffer to get pixel the refracted ray hits.
  17487. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  17488. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  17489. }
  17490. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  17491. const dotNV = n.dot( v ).clamp();
  17492. // Get the specular component.
  17493. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  17494. dotNV,
  17495. specularColor,
  17496. specularF90,
  17497. roughness
  17498. } ) );
  17499. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  17500. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  17501. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  17502. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  17503. } );
  17504. //
  17505. // Iridescence
  17506. //
  17507. // XYZ to linear-sRGB color space
  17508. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  17509. 3.2404542, -1.5371385, -0.4985314,
  17510. -0.969266, 1.8760108, 0.0415560,
  17511. 0.0556434, -0.2040259, 1.0572252
  17512. );
  17513. // Assume air interface for top
  17514. // Note: We don't handle the case fresnel0 == 1
  17515. const Fresnel0ToIor = ( fresnel0 ) => {
  17516. const sqrtF0 = fresnel0.sqrt();
  17517. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  17518. };
  17519. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  17520. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  17521. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  17522. };
  17523. // Fresnel equations for dielectric/dielectric interfaces.
  17524. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  17525. // Evaluation XYZ sensitivity curves in Fourier space
  17526. const evalSensitivity = ( OPD, shift ) => {
  17527. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  17528. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  17529. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  17530. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  17531. 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( -45282e5 ).exp() );
  17532. 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() );
  17533. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  17534. const rgb = XYZ_TO_REC709.mul( xyz );
  17535. return rgb;
  17536. };
  17537. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  17538. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  17539. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  17540. // Evaluate the cosTheta on the base layer (Snell law)
  17541. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  17542. // Handle TIR:
  17543. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  17544. If( cosTheta2Sq.lessThan( 0 ), () => {
  17545. return vec3( 1.0 );
  17546. } );
  17547. const cosTheta2 = cosTheta2Sq.sqrt();
  17548. // First interface
  17549. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  17550. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  17551. //const R21 = R12;
  17552. const T121 = R12.oneMinus();
  17553. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  17554. const phi21 = float( Math.PI ).sub( phi12 );
  17555. // Second interface
  17556. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  17557. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  17558. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  17559. const phi23 = vec3(
  17560. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  17561. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  17562. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  17563. );
  17564. // Phase shift
  17565. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  17566. const phi = vec3( phi21 ).add( phi23 );
  17567. // Compound terms
  17568. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  17569. const r123 = R123.sqrt();
  17570. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  17571. // Reflectance term for m = 0 (DC term amplitude)
  17572. const C0 = R12.add( Rs );
  17573. const I = C0.toVar();
  17574. // Reflectance term for m > 0 (pairs of diracs)
  17575. const Cm = Rs.sub( T121 ).toVar();
  17576. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  17577. Cm.mulAssign( r123 );
  17578. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  17579. I.addAssign( Cm.mul( Sm ) );
  17580. } );
  17581. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  17582. return I.max( vec3( 0.0 ) );
  17583. } ).setLayout( {
  17584. name: 'evalIridescence',
  17585. type: 'vec3',
  17586. inputs: [
  17587. { name: 'outsideIOR', type: 'float' },
  17588. { name: 'eta2', type: 'float' },
  17589. { name: 'cosTheta1', type: 'float' },
  17590. { name: 'thinFilmThickness', type: 'float' },
  17591. { name: 'baseF0', type: 'vec3' }
  17592. ]
  17593. } );
  17594. //
  17595. // Sheen
  17596. //
  17597. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  17598. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF".
  17599. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  17600. const dotNV = normal.dot( viewDir ).saturate();
  17601. const r2 = roughness.mul( roughness );
  17602. const rInv = roughness.add( 0.1 ).reciprocal();
  17603. const a = float( -1.9362 ).add( roughness.mul( 1.0678 ) ).add( r2.mul( 0.4573 ) ).sub( rInv.mul( 0.8469 ) );
  17604. const b = float( -0.6014 ).add( roughness.mul( 0.5538 ) ).sub( r2.mul( 0.4670 ) ).sub( rInv.mul( 0.1255 ) );
  17605. const DG = a.mul( dotNV ).add( b ).exp();
  17606. return DG.saturate();
  17607. } );
  17608. const clearcoatF0 = vec3( 0.04 );
  17609. const clearcoatF90 = float( 1 );
  17610. /**
  17611. * Represents the lighting model for a PBR material.
  17612. *
  17613. * @augments LightingModel
  17614. */
  17615. class PhysicalLightingModel extends LightingModel {
  17616. /**
  17617. * Constructs a new physical lighting model.
  17618. *
  17619. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  17620. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  17621. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  17622. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  17623. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  17624. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  17625. * @param {boolean} [retroreflective=false] - Whether retroreflection is supported or not.
  17626. */
  17627. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, retroreflective = false ) {
  17628. super();
  17629. /**
  17630. * Whether clearcoat is supported or not.
  17631. *
  17632. * @type {boolean}
  17633. * @default false
  17634. */
  17635. this.clearcoat = clearcoat;
  17636. /**
  17637. * Whether sheen is supported or not.
  17638. *
  17639. * @type {boolean}
  17640. * @default false
  17641. */
  17642. this.sheen = sheen;
  17643. /**
  17644. * Whether iridescence is supported or not.
  17645. *
  17646. * @type {boolean}
  17647. * @default false
  17648. */
  17649. this.iridescence = iridescence;
  17650. /**
  17651. * Whether anisotropy is supported or not.
  17652. *
  17653. * @type {boolean}
  17654. * @default false
  17655. */
  17656. this.anisotropy = anisotropy;
  17657. /**
  17658. * Whether transmission is supported or not.
  17659. *
  17660. * @type {boolean}
  17661. * @default false
  17662. */
  17663. this.transmission = transmission;
  17664. /**
  17665. * Whether dispersion is supported or not.
  17666. *
  17667. * @type {boolean}
  17668. * @default false
  17669. */
  17670. this.dispersion = dispersion;
  17671. /**
  17672. * Whether retroreflection is supported or not.
  17673. *
  17674. * @type {boolean}
  17675. * @default false
  17676. */
  17677. this.retroreflective = retroreflective;
  17678. /**
  17679. * The clear coat radiance.
  17680. *
  17681. * @type {?Node}
  17682. * @default null
  17683. */
  17684. this.clearcoatRadiance = null;
  17685. /**
  17686. * The clear coat specular direct.
  17687. *
  17688. * @type {?Node}
  17689. * @default null
  17690. */
  17691. this.clearcoatSpecularDirect = null;
  17692. /**
  17693. * The clear coat specular indirect.
  17694. *
  17695. * @type {?Node}
  17696. * @default null
  17697. */
  17698. this.clearcoatSpecularIndirect = null;
  17699. /**
  17700. * The sheen specular direct.
  17701. *
  17702. * @type {?Node}
  17703. * @default null
  17704. */
  17705. this.sheenSpecularDirect = null;
  17706. /**
  17707. * The sheen specular indirect.
  17708. *
  17709. * @type {?Node}
  17710. * @default null
  17711. */
  17712. this.sheenSpecularIndirect = null;
  17713. /**
  17714. * The iridescence Fresnel.
  17715. *
  17716. * @type {?Node}
  17717. * @default null
  17718. */
  17719. this.iridescenceFresnel = null;
  17720. /**
  17721. * The iridescence F0 dielectric.
  17722. *
  17723. * @type {?Node}
  17724. * @default null
  17725. */
  17726. this.iridescenceF0Dielectric = null;
  17727. /**
  17728. * The iridescence F0 metallic.
  17729. *
  17730. * @type {?Node}
  17731. * @default null
  17732. */
  17733. this.iridescenceF0Metallic = null;
  17734. }
  17735. /**
  17736. * Depending on what features are requested, the method prepares certain node variables
  17737. * which are later used for lighting computations.
  17738. *
  17739. * @param {NodeBuilder} builder - The current node builder.
  17740. */
  17741. start( builder ) {
  17742. if ( this.clearcoat === true ) {
  17743. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  17744. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  17745. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  17746. }
  17747. if ( this.sheen === true ) {
  17748. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  17749. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  17750. }
  17751. if ( this.iridescence === true ) {
  17752. const dotNVi = normalView.dot( positionViewDirection ).clamp();
  17753. const iridescenceFresnelDielectric = evalIridescence( {
  17754. outsideIOR: float( 1.0 ),
  17755. eta2: iridescenceIOR,
  17756. cosTheta1: dotNVi,
  17757. thinFilmThickness: iridescenceThickness,
  17758. baseF0: specularColor
  17759. } );
  17760. const iridescenceFresnelMetallic = evalIridescence( {
  17761. outsideIOR: float( 1.0 ),
  17762. eta2: iridescenceIOR,
  17763. cosTheta1: dotNVi,
  17764. thinFilmThickness: iridescenceThickness,
  17765. baseF0: diffuseColor.rgb
  17766. } );
  17767. this.iridescenceFresnel = mix( iridescenceFresnelDielectric, iridescenceFresnelMetallic, metalness );
  17768. this.iridescenceF0Dielectric = Schlick_to_F0( { f: iridescenceFresnelDielectric, f90: 1.0, dotVH: dotNVi } );
  17769. this.iridescenceF0Metallic = Schlick_to_F0( { f: iridescenceFresnelMetallic, f90: 1.0, dotVH: dotNVi } );
  17770. }
  17771. if ( this.transmission === true ) {
  17772. const position = positionWorld;
  17773. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  17774. const n = normalWorld;
  17775. const context = builder.context;
  17776. context.backdrop = getIBLVolumeRefraction(
  17777. n,
  17778. v,
  17779. roughness,
  17780. diffuseContribution,
  17781. specularColorBlended,
  17782. specularF90, // specularF90
  17783. position, // positionWorld
  17784. modelWorldMatrix, // modelMatrix
  17785. cameraViewMatrix, // viewMatrix
  17786. cameraProjectionMatrix, // projMatrix
  17787. ior,
  17788. thickness,
  17789. attenuationColor,
  17790. attenuationDistance,
  17791. this.dispersion ? dispersion : null
  17792. );
  17793. context.backdropAlpha = transmission;
  17794. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  17795. }
  17796. super.start( builder );
  17797. }
  17798. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  17799. // Approximates multi-scattering in order to preserve energy.
  17800. // http://www.jcgt.org/published/0008/01/03/
  17801. computeMultiscattering( singleScatter, multiScatter, specularF90, f0, iridescenceF0 = null ) {
  17802. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  17803. const fab = DFGLUT( { roughness, dotNV } );
  17804. const Fr = iridescenceF0 ? iridescence.mix( f0, iridescenceF0 ) : f0;
  17805. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  17806. const Ess = fab.x.add( fab.y );
  17807. const Ems = Ess.oneMinus();
  17808. const Favg = Fr.add( Fr.oneMinus().mul( 0.047619 ) ); // 1/21
  17809. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  17810. singleScatter.addAssign( FssEss );
  17811. multiScatter.addAssign( Fms.mul( Ems ) );
  17812. }
  17813. /**
  17814. * Implements the direct light.
  17815. *
  17816. * @param {Object} lightData - The light data.
  17817. * @param {NodeBuilder} builder - The current node builder.
  17818. */
  17819. direct( { lightDirection, lightColor, reflectedLight }, /* builder */ ) {
  17820. const dotNL = normalView.dot( lightDirection ).clamp();
  17821. const irradiance = dotNL.mul( lightColor ).toVar();
  17822. if ( this.sheen === true ) {
  17823. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  17824. const sheenAlbedoV = IBLSheenBRDF( { normal: normalView, viewDir: positionViewDirection, roughness: sheenRoughness } );
  17825. const sheenAlbedoL = IBLSheenBRDF( { normal: normalView, viewDir: lightDirection, roughness: sheenRoughness } );
  17826. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( sheenAlbedoV.max( sheenAlbedoL ) ).oneMinus();
  17827. irradiance.mulAssign( sheenEnergyComp );
  17828. }
  17829. if ( this.clearcoat === true ) {
  17830. const dotNLcc = clearcoatNormalView.dot( lightDirection ).clamp();
  17831. const ccIrradiance = dotNLcc.mul( lightColor );
  17832. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: clearcoatNormalView } ) ) );
  17833. }
  17834. // Light reflected by the specular interface is not available to the diffuse layer ( glTF fresnel_mix )
  17835. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  17836. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  17837. const F = F_Schlick( { f0: specularColor, f90: specularF90, dotVH } );
  17838. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseContribution } ) ).mul( F.oneMinus() ) );
  17839. let specularBRDF = BRDF_GGX( { lightDirection, f0: specularColorBlended, f90: 1, roughness, f: this.iridescenceFresnel, USE_IRIDESCENCE: this.iridescence, USE_ANISOTROPY: this.anisotropy } );
  17840. if ( this.retroreflective === true ) {
  17841. // Minimal Retroreflective Microfacet Model:
  17842. // https://jcgt.org/published/0015/01/04/
  17843. const retroViewDirection = positionViewDirection.negate().reflect( normalView );
  17844. const retroSpecularBRDF = BRDF_GGX( { lightDirection, viewDirection: retroViewDirection, f0: specularColorBlended, f90: 1, roughness, f: this.iridescenceFresnel, USE_IRIDESCENCE: this.iridescence, USE_ANISOTROPY: this.anisotropy } );
  17845. specularBRDF = mix( specularBRDF, retroSpecularBRDF, retroreflective.clamp() );
  17846. }
  17847. // Multi-scattering energy compensation for direct lighting
  17848. // Based on "Practical Multiple Scattering Compensation for Microfacet Models"
  17849. // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf
  17850. const dotNV = normalView.dot( positionViewDirection ).clamp();
  17851. const fab = DFGLUT( { roughness, dotNV } );
  17852. // Energy of the single-scattering lobe in a white furnace ( F0 = F90 = 1 )
  17853. const Ess = fab.x.add( fab.y );
  17854. // Compensate for the energy lost to multiple scattering, tinting the added term by F0 ( equation 16 )
  17855. const energyCompensation = specularColorBlended.mul( Ess.reciprocal().sub( 1.0 ) ).add( 1.0 );
  17856. reflectedLight.directSpecular.addAssign( irradiance.mul( specularBRDF ).mul( energyCompensation ) );
  17857. }
  17858. /**
  17859. * This method is intended for implementing the direct light term for
  17860. * rect area light nodes.
  17861. *
  17862. * @param {Object} input - The input data.
  17863. * @param {NodeBuilder} builder - The current node builder.
  17864. */
  17865. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 }, /* builder */ ) {
  17866. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  17867. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  17868. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  17869. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  17870. const N = normalView;
  17871. const V = positionViewDirection;
  17872. const P = positionView.toVar();
  17873. const uv = LTC_Uv( { N, V, roughness } );
  17874. const t1 = ltc_1.sample( uv ).toVar();
  17875. const t2 = ltc_2.sample( uv ).toVar();
  17876. const mInv = mat3(
  17877. vec3( t1.x, 0, t1.y ),
  17878. vec3( 0, 1, 0 ),
  17879. vec3( t1.z, 0, t1.w )
  17880. ).toVar();
  17881. // LTC Fresnel Approximation by Stephen Hill
  17882. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  17883. const fresnel = specularColorBlended.mul( t2.x ).add( specularF90.sub( specularColorBlended ).mul( t2.y ) ).toVar();
  17884. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  17885. reflectedLight.directDiffuse.addAssign( lightColor.mul( diffuseContribution ).mul( LTC_Evaluate( { N, V, P, mInv: mat3( 1, 0, 0, 0, 1, 0, 0, 0, 1 ), p0, p1, p2, p3 } ) ) );
  17886. if ( this.clearcoat === true ) {
  17887. const Ncc = clearcoatNormalView;
  17888. const uvClearcoat = LTC_Uv( { N: Ncc, V, roughness: clearcoatRoughness } );
  17889. const t1Clearcoat = ltc_1.sample( uvClearcoat );
  17890. const t2Clearcoat = ltc_2.sample( uvClearcoat );
  17891. const mInvClearcoat = mat3(
  17892. vec3( t1Clearcoat.x, 0, t1Clearcoat.y ),
  17893. vec3( 0, 1, 0 ),
  17894. vec3( t1Clearcoat.z, 0, t1Clearcoat.w )
  17895. );
  17896. // LTC Fresnel Approximation for clearcoat
  17897. const fresnelClearcoat = clearcoatF0.mul( t2Clearcoat.x ).add( clearcoatF90.sub( clearcoatF0 ).mul( t2Clearcoat.y ) );
  17898. this.clearcoatSpecularDirect.addAssign( lightColor.mul( fresnelClearcoat ).mul( LTC_Evaluate( { N: Ncc, V, P, mInv: mInvClearcoat, p0, p1, p2, p3 } ) ) );
  17899. }
  17900. }
  17901. /**
  17902. * Implements the indirect lighting.
  17903. *
  17904. * @param {NodeBuilder} builder - The current node builder.
  17905. */
  17906. indirect( builder ) {
  17907. this.indirectDiffuse( builder );
  17908. this.indirectSpecular( builder );
  17909. this.ambientOcclusion( builder );
  17910. }
  17911. /**
  17912. * Implements the indirect diffuse term.
  17913. *
  17914. * @param {NodeBuilder} builder - The current node builder.
  17915. */
  17916. indirectDiffuse( builder ) {
  17917. const { irradiance, reflectedLight } = builder.context;
  17918. // Energy reflected by the specular lobe is not available to the diffuse layer
  17919. const singleScattering = vec3().toVar();
  17920. const multiScattering = vec3().toVar();
  17921. this.computeMultiscattering( singleScattering, multiScattering, specularF90, specularColor, this.iridescenceF0Dielectric );
  17922. const diffuse = irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseContribution } ) ).mul( singleScattering.add( multiScattering ).oneMinus() ).toVar();
  17923. if ( this.sheen === true ) {
  17924. const sheenAlbedo = IBLSheenBRDF( { normal: normalView, viewDir: positionViewDirection, roughness: sheenRoughness } );
  17925. this.sheenSpecularIndirect.addAssign( irradiance.mul( sheen, sheenAlbedo, 1 / Math.PI ) );
  17926. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( sheenAlbedo ).oneMinus();
  17927. diffuse.mulAssign( sheenEnergyComp );
  17928. }
  17929. reflectedLight.indirectDiffuse.addAssign( diffuse );
  17930. }
  17931. /**
  17932. * Implements the indirect specular term.
  17933. *
  17934. * @param {NodeBuilder} builder - The current node builder.
  17935. */
  17936. indirectSpecular( builder ) {
  17937. const { radiance, iblIrradiance, reflectedLight } = builder.context;
  17938. if ( this.sheen === true ) {
  17939. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  17940. sheen,
  17941. IBLSheenBRDF( {
  17942. normal: normalView,
  17943. viewDir: positionViewDirection,
  17944. roughness: sheenRoughness
  17945. } ),
  17946. 1 / Math.PI
  17947. ) );
  17948. }
  17949. if ( this.clearcoat === true ) {
  17950. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  17951. const clearcoatEnv = EnvironmentBRDF( {
  17952. dotNV: dotNVcc,
  17953. specularColor: clearcoatF0,
  17954. specularF90: clearcoatF90,
  17955. roughness: clearcoatRoughness
  17956. } );
  17957. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  17958. }
  17959. // Both indirect specular and indirect diffuse light accumulate here
  17960. // Compute multiscattering separately for dielectric and metallic, then mix
  17961. const singleScatteringDielectric = vec3().toVar( 'singleScatteringDielectric' );
  17962. const multiScatteringDielectric = vec3().toVar( 'multiScatteringDielectric' );
  17963. const singleScatteringMetallic = vec3().toVar( 'singleScatteringMetallic' );
  17964. const multiScatteringMetallic = vec3().toVar( 'multiScatteringMetallic' );
  17965. this.computeMultiscattering( singleScatteringDielectric, multiScatteringDielectric, specularF90, specularColor, this.iridescenceF0Dielectric );
  17966. this.computeMultiscattering( singleScatteringMetallic, multiScatteringMetallic, specularF90, diffuseColor.rgb, this.iridescenceF0Metallic );
  17967. // Mix based on metalness
  17968. const singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, metalness );
  17969. const multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, metalness );
  17970. // Diffuse energy conservation uses dielectric path
  17971. const totalScatteringDielectric = singleScatteringDielectric.add( multiScatteringDielectric );
  17972. const diffuse = diffuseContribution.mul( totalScatteringDielectric.oneMinus() );
  17973. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  17974. const indirectSpecular = radiance.mul( singleScattering ).add( multiScattering.mul( cosineWeightedIrradiance ) ).toVar();
  17975. const indirectDiffuse = diffuse.mul( cosineWeightedIrradiance ).toVar();
  17976. if ( this.sheen === true ) {
  17977. const sheenAlbedo = IBLSheenBRDF( { normal: normalView, viewDir: positionViewDirection, roughness: sheenRoughness } );
  17978. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( sheenAlbedo ).oneMinus();
  17979. indirectSpecular.mulAssign( sheenEnergyComp );
  17980. indirectDiffuse.mulAssign( sheenEnergyComp );
  17981. }
  17982. reflectedLight.indirectSpecular.addAssign( indirectSpecular );
  17983. reflectedLight.indirectDiffuse.addAssign( indirectDiffuse );
  17984. }
  17985. /**
  17986. * Implements the ambient occlusion term.
  17987. *
  17988. * @param {NodeBuilder} builder - The current node builder.
  17989. */
  17990. ambientOcclusion( builder ) {
  17991. const { ambientOcclusion, reflectedLight } = builder.context;
  17992. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  17993. const aoNV = dotNV.add( ambientOcclusion );
  17994. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  17995. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  17996. if ( this.clearcoat === true ) {
  17997. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  17998. }
  17999. if ( this.sheen === true ) {
  18000. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  18001. }
  18002. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  18003. reflectedLight.indirectSpecular.mulAssign( aoNode );
  18004. }
  18005. /**
  18006. * Used for final lighting accumulations depending on the requested features.
  18007. *
  18008. * @param {NodeBuilder} builder - The current node builder.
  18009. */
  18010. finish( { context } ) {
  18011. const { outgoingLight } = context;
  18012. if ( this.clearcoat === true ) {
  18013. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  18014. const Fcc = F_Schlick( {
  18015. dotVH: dotNVcc,
  18016. f0: clearcoatF0,
  18017. f90: clearcoatF90
  18018. } );
  18019. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  18020. outgoingLight.assign( clearcoatLight );
  18021. }
  18022. if ( this.sheen === true ) {
  18023. const sheenLight = outgoingLight.add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  18024. outgoingLight.assign( sheenLight );
  18025. }
  18026. }
  18027. }
  18028. const GOLDEN_ANGLE = 2.399963229728653;
  18029. // These defines must match with PMREMGenerator
  18030. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  18031. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  18032. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  18033. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  18034. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  18035. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  18036. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  18037. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  18038. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  18039. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  18040. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  18041. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  18042. // These shader functions convert between the UV coordinates of a single face of
  18043. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  18044. // sampling a textureCube (not generally normalized ).
  18045. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  18046. const absDirection = vec3( abs( direction ) ).toVar();
  18047. const face = float( -1 ).toVar();
  18048. If( absDirection.x.greaterThan( absDirection.z ), () => {
  18049. If( absDirection.x.greaterThan( absDirection.y ), () => {
  18050. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  18051. } ).Else( () => {
  18052. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  18053. } );
  18054. } ).Else( () => {
  18055. If( absDirection.z.greaterThan( absDirection.y ), () => {
  18056. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  18057. } ).Else( () => {
  18058. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  18059. } );
  18060. } );
  18061. return face;
  18062. } ).setLayout( {
  18063. name: 'getFace',
  18064. type: 'float',
  18065. inputs: [
  18066. { name: 'direction', type: 'vec3' }
  18067. ]
  18068. } );
  18069. // RH coordinate system; PMREM face-indexing convention
  18070. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  18071. const uv = vec2().toVar();
  18072. If( face.equal( 0.0 ), () => {
  18073. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  18074. } ).ElseIf( face.equal( 1.0 ), () => {
  18075. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  18076. } ).ElseIf( face.equal( 2.0 ), () => {
  18077. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  18078. } ).ElseIf( face.equal( 3.0 ), () => {
  18079. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  18080. } ).ElseIf( face.equal( 4.0 ), () => {
  18081. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  18082. } ).Else( () => {
  18083. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  18084. } );
  18085. return mul( 0.5, uv.add( 1.0 ) );
  18086. } ).setLayout( {
  18087. name: 'getUV',
  18088. type: 'vec2',
  18089. inputs: [
  18090. { name: 'direction', type: 'vec3' },
  18091. { name: 'face', type: 'float' }
  18092. ]
  18093. } );
  18094. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  18095. const mip = float( 0.0 ).toVar();
  18096. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  18097. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  18098. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  18099. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  18100. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  18101. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  18102. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  18103. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  18104. } ).Else( () => {
  18105. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  18106. } );
  18107. return mip;
  18108. } ).setLayout( {
  18109. name: 'roughnessToMip',
  18110. type: 'float',
  18111. inputs: [
  18112. { name: 'roughness', type: 'float' }
  18113. ]
  18114. } );
  18115. //
  18116. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  18117. const roughness = float( roughness_immutable );
  18118. const sampleDir = vec3( sampleDir_immutable );
  18119. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  18120. const mipF = fract( mip );
  18121. const mipInt = floor( mip );
  18122. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  18123. If( mipF.notEqual( 0.0 ), () => {
  18124. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  18125. color0.assign( mix( color0, color1, mipF ) );
  18126. } );
  18127. return color0;
  18128. } );
  18129. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  18130. const mipInt = float( mipInt_immutable ).toVar();
  18131. const direction = vec3( direction_immutable );
  18132. const face = float( getFace( direction ) ).toVar();
  18133. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  18134. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  18135. const faceSize = float( exp2( mipInt ) ).toVar();
  18136. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  18137. If( face.greaterThan( 2.0 ), () => {
  18138. uv.y.addAssign( faceSize );
  18139. face.subAssign( 3.0 );
  18140. } );
  18141. uv.x.addAssign( face.mul( faceSize ) );
  18142. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  18143. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  18144. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  18145. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  18146. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  18147. } );
  18148. // Gaussian blur along a golden-angle spiral, importance-sampled by stratified
  18149. // inverse-CDF so every sample carries equal Gaussian weight.
  18150. const sphericalGaussianBlur = /*@__PURE__*/ Fn( ( { SAMPLES, sigma, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  18151. const color = vec3( 0.0 ).toVar();
  18152. If( sigma.equal( 0.0 ), () => {
  18153. color.assign( bilinearCubeUV( envMap, outputDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) );
  18154. } ).Else( () => {
  18155. const up = select( abs( outputDirection.z ).lessThan( 0.999 ), vec3( 0.0, 0.0, 1.0 ), vec3( 1.0, 0.0, 0.0 ) );
  18156. const tangent = normalize( cross( up, outputDirection ) ).toVar();
  18157. const bitangent = cross( outputDirection, tangent ).toVar();
  18158. // Truncate the kernel at three standard deviations or at the antipode.
  18159. const thetaMax = min$1( sigma.mul( 3.0 ), Math.PI );
  18160. const truncation = exp( thetaMax.mul( thetaMax ).mul( -0.5 ).div( sigma.mul( sigma ) ) ).oneMinus().toVar();
  18161. const accumWeight = float( 0.0 ).toVar();
  18162. Loop( { start: int( 0 ), end: SAMPLES }, ( { i } ) => {
  18163. // Stratified inverse-CDF sampling of the Gaussian, placed on a golden-angle spiral.
  18164. const stratum = float( i ).add( 0.5 ).div( float( SAMPLES ) );
  18165. const theta = sigma.mul( sqrt( log( stratum.mul( truncation ).oneMinus() ).mul( -2 ) ) ).toVar();
  18166. const phi = float( i ).mul( GOLDEN_ANGLE ).toVar();
  18167. const offset = tangent.mul( cos( phi ) ).add( bitangent.mul( sin( phi ) ) );
  18168. const sampleDirection = outputDirection.mul( cos( theta ) ).add( offset.mul( sin( theta ) ) );
  18169. // Correct the planar sample density to solid angle.
  18170. const weight = sin( theta ).div( theta ).toVar();
  18171. color.addAssign( bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ).mul( weight ) );
  18172. accumWeight.addAssign( weight );
  18173. } );
  18174. color.divAssign( accumWeight );
  18175. } );
  18176. return vec4( color, 1.0 );
  18177. } );
  18178. // GGX VNDF importance sampling functions
  18179. // Van der Corput radical inverse for generating quasi-random sequences
  18180. const radicalInverse_VdC = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  18181. const bits = uint( bits_immutable ).toVar();
  18182. bits.assign( bits.shiftLeft( uint( 16 ) ).bitOr( bits.shiftRight( uint( 16 ) ) ) );
  18183. bits.assign( bits.bitAnd( uint( 0x55555555 ) ).shiftLeft( uint( 1 ) ).bitOr( bits.bitAnd( uint( 0xAAAAAAAA ) ).shiftRight( uint( 1 ) ) ) );
  18184. bits.assign( bits.bitAnd( uint( 0x33333333 ) ).shiftLeft( uint( 2 ) ).bitOr( bits.bitAnd( uint( 0xCCCCCCCC ) ).shiftRight( uint( 2 ) ) ) );
  18185. bits.assign( bits.bitAnd( uint( 0x0F0F0F0F ) ).shiftLeft( uint( 4 ) ).bitOr( bits.bitAnd( uint( 0xF0F0F0F0 ) ).shiftRight( uint( 4 ) ) ) );
  18186. bits.assign( bits.bitAnd( uint( 0x00FF00FF ) ).shiftLeft( uint( 8 ) ).bitOr( bits.bitAnd( uint( 0xFF00FF00 ) ).shiftRight( uint( 8 ) ) ) );
  18187. return float( bits ).mul( 2.3283064365386963e-10 ); // / 0x100000000
  18188. } );
  18189. // Hammersley sequence for quasi-Monte Carlo sampling
  18190. const hammersley = /*@__PURE__*/ Fn( ( [ i, N ] ) => {
  18191. return vec2( float( i ).div( float( N ) ), radicalInverse_VdC( i ) );
  18192. } );
  18193. // GGX VNDF importance sampling (Eric Heitz 2018)
  18194. // "Sampling the GGX Distribution of Visible Normals"
  18195. // https://jcgt.org/published/0007/04/01/
  18196. const importanceSampleGGX_VNDF = /*@__PURE__*/ Fn( ( [ Xi, V, roughness ] ) => {
  18197. const alpha = roughness.mul( roughness ).toConst();
  18198. // Section 4.1: Orthonormal basis
  18199. const T1 = vec3( 1.0, 0.0, 0.0 ).toConst();
  18200. const T2 = cross( V, T1 ).toConst();
  18201. // Section 4.2: Parameterization of projected area
  18202. const r = sqrt( Xi.x ).toConst();
  18203. const phi = mul( 2.0, 3.14159265359 ).mul( Xi.y ).toConst();
  18204. const t1 = r.mul( cos( phi ) ).toConst();
  18205. const t2 = r.mul( sin( phi ) ).toVar();
  18206. const s = mul( 0.5, V.z.add( 1.0 ) ).toConst();
  18207. t2.assign( s.oneMinus().mul( sqrt( t1.mul( t1 ).oneMinus() ) ).add( s.mul( t2 ) ) );
  18208. // Section 4.3: Reprojection onto hemisphere
  18209. const Nh = T1.mul( t1 ).add( T2.mul( t2 ) ).add( V.mul( sqrt( max$1( 0.0, t1.mul( t1 ).add( t2.mul( t2 ) ).oneMinus() ) ) ) );
  18210. // Section 3.4: Transform back to ellipsoid configuration
  18211. return normalize( vec3( alpha.mul( Nh.x ), alpha.mul( Nh.y ), max$1( 0.0, Nh.z ) ) );
  18212. } );
  18213. // GGX convolution using VNDF importance sampling
  18214. const ggxConvolution = /*@__PURE__*/ Fn( ( { roughness, mipInt, envMap, N_immutable, GGX_SAMPLES, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  18215. const N = vec3( N_immutable ).toVar();
  18216. const prefilteredColor = vec3( 0.0 ).toVar();
  18217. const totalWeight = float( 0.0 ).toVar();
  18218. // For very low roughness, just sample the environment directly
  18219. If( roughness.lessThan( 0.001 ), () => {
  18220. prefilteredColor.assign( bilinearCubeUV( envMap, N, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) );
  18221. } ).Else( () => {
  18222. // Tangent space basis for VNDF sampling
  18223. const up = select( abs( N.z ).lessThan( 0.999 ), vec3( 0.0, 0.0, 1.0 ), vec3( 1.0, 0.0, 0.0 ) );
  18224. const tangent = normalize( cross( up, N ) ).toVar();
  18225. const bitangent = cross( N, tangent ).toVar();
  18226. Loop( { start: uint( 0 ), end: GGX_SAMPLES }, ( { i } ) => {
  18227. const Xi = hammersley( i, GGX_SAMPLES );
  18228. // For PMREM, V = N, so in tangent space V is always (0, 0, 1)
  18229. const H_tangent = importanceSampleGGX_VNDF( Xi, vec3( 0.0, 0.0, 1.0 ), roughness );
  18230. // Transform H back to world space
  18231. const H = normalize( tangent.mul( H_tangent.x ).add( bitangent.mul( H_tangent.y ) ).add( N.mul( H_tangent.z ) ) );
  18232. const L = normalize( H.mul( dot( N, H ).mul( 2.0 ) ).sub( N ) );
  18233. const NdotL = max$1( dot( N, L ), 0.0 );
  18234. If( NdotL.greaterThan( 0.0 ), () => {
  18235. // Sample environment at fixed mip level
  18236. // VNDF importance sampling handles the distribution filtering
  18237. const sampleColor = bilinearCubeUV( envMap, L, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  18238. // Weight by NdotL for the split-sum approximation
  18239. // VNDF PDF naturally accounts for the visible microfacet distribution
  18240. prefilteredColor.addAssign( sampleColor.mul( NdotL ) );
  18241. totalWeight.addAssign( NdotL );
  18242. } );
  18243. } );
  18244. If( totalWeight.greaterThan( 0.0 ), () => {
  18245. prefilteredColor.assign( prefilteredColor.div( totalWeight ) );
  18246. } );
  18247. } );
  18248. return vec4( prefilteredColor, 1.0 );
  18249. } );
  18250. const LOD_MIN = 4;
  18251. // The number of extra mips.
  18252. // Used for scene blur in fromScene() method.
  18253. const EXTRA_LODS = 6;
  18254. // The number of spiral samples per blur pass.
  18255. // Used for scene blur in fromScene() method.
  18256. const BLUR_SAMPLES = 20;
  18257. // GGX VNDF importance sampling configuration
  18258. const GGX_SAMPLES = 256;
  18259. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  18260. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  18261. const _clearColor$2 = /*@__PURE__*/ new Color();
  18262. let _oldTarget = null;
  18263. let _oldActiveCubeFace = 0;
  18264. let _oldActiveMipmapLevel = 0;
  18265. const _origin = /*@__PURE__*/ new Vector3();
  18266. const _direction = /*@__PURE__*/ new Vector3();
  18267. // maps blur materials to their uniforms dictionary
  18268. const _uniformsMap = new WeakMap();
  18269. // WebGPU Face indices
  18270. const _faceLib = [
  18271. 3, 1, 5,
  18272. 0, 4, 2
  18273. ];
  18274. const _outputDirection = /*@__PURE__*/ attribute( 'outputDirection' ).normalize();
  18275. /**
  18276. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  18277. * (PMREM) from a cubeMap environment texture. This allows different levels of
  18278. * blur to be quickly accessed based on material roughness. It is packed into a
  18279. * special CubeUV format that allows us to perform custom interpolation so that
  18280. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  18281. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  18282. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  18283. * higher roughness levels. In this way we maintain resolution to smoothly
  18284. * interpolate diffuse lighting while limiting sampling computation.
  18285. *
  18286. * The prefiltering uses GGX VNDF (Visible Normal Distribution Function)
  18287. * importance sampling based on "Sampling the GGX Distribution of Visible Normals"
  18288. * (Heitz, 2018) to generate environment maps that accurately match the GGX BRDF
  18289. * used in material rendering for physically-based image-based lighting.
  18290. */
  18291. class PMREMGenerator {
  18292. /**
  18293. * Constructs a new PMREM generator.
  18294. *
  18295. * @param {Renderer} renderer - The renderer.
  18296. */
  18297. constructor( renderer ) {
  18298. this._renderer = renderer;
  18299. this._pingPongRenderTarget = null;
  18300. this._lodMax = 0;
  18301. this._cubeSize = 0;
  18302. this._sizeLods = [];
  18303. this._lodMeshes = [];
  18304. this._blurMaterial = null;
  18305. this._ggxMaterial = null;
  18306. this._cubemapMaterial = null;
  18307. this._equirectMaterial = null;
  18308. this._backgroundBox = null;
  18309. }
  18310. get _hasInitialized() {
  18311. return this._renderer.hasInitialized();
  18312. }
  18313. /**
  18314. * Generates a PMREM from a supplied Scene, which can be faster than using an
  18315. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  18316. * in radians to be applied to the scene before PMREM generation. Optional near
  18317. * and far planes ensure the scene is rendered in its entirety.
  18318. *
  18319. * @param {Scene} scene - The scene to be captured.
  18320. * @param {number} [sigma=0] - The blur radius in radians.
  18321. * @param {number} [near=0.1] - The near plane distance.
  18322. * @param {number} [far=100] - The far plane distance.
  18323. * @param {Object} [options={}] - The configuration options.
  18324. * @param {number} [options.size=256] - The texture size of the PMREM.
  18325. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  18326. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  18327. * @return {RenderTarget} The resulting PMREM.
  18328. * @see {@link PMREMGenerator#fromScene}
  18329. */
  18330. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  18331. const {
  18332. size = 256,
  18333. position = _origin,
  18334. renderTarget = null,
  18335. } = options;
  18336. this._setSize( size );
  18337. if ( this._hasInitialized === false ) {
  18338. throw new Error( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Use "await renderer.init();" before using this method.' );
  18339. }
  18340. _oldTarget = this._renderer.getRenderTarget();
  18341. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  18342. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  18343. const cubeUVRenderTarget = renderTarget || this._allocateTarget( true );
  18344. this._init( cubeUVRenderTarget );
  18345. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  18346. if ( sigma > 0 ) {
  18347. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  18348. }
  18349. this._applyPMREM( cubeUVRenderTarget );
  18350. this._cleanup( cubeUVRenderTarget );
  18351. return cubeUVRenderTarget;
  18352. }
  18353. /**
  18354. * Generates a PMREM from a supplied Scene, which can be faster than using an
  18355. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  18356. * in radians to be applied to the scene before PMREM generation. Optional near
  18357. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  18358. * is placed at the origin).
  18359. *
  18360. * @deprecated
  18361. * @param {Scene} scene - The scene to be captured.
  18362. * @param {number} [sigma=0] - The blur radius in radians.
  18363. * @param {number} [near=0.1] - The near plane distance.
  18364. * @param {number} [far=100] - The far plane distance.
  18365. * @param {Object} [options={}] - The configuration options.
  18366. * @param {number} [options.size=256] - The texture size of the PMREM.
  18367. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  18368. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  18369. * @return {Promise<RenderTarget>} A Promise that resolve with the PMREM when the generation has been finished.
  18370. * @see {@link PMREMGenerator#fromScene}
  18371. */
  18372. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  18373. warnOnce( 'PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  18374. await this._renderer.init();
  18375. return this.fromScene( scene, sigma, near, far, options );
  18376. }
  18377. /**
  18378. * Generates a PMREM from an equirectangular texture, which can be either LDR
  18379. * or HDR. The ideal input image size is 1k (1024 x 512), as this matches best
  18380. * with the 256 x 256 cubemap output. The minimum supported input image size
  18381. * is 64 x 32.
  18382. *
  18383. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  18384. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  18385. * @return {RenderTarget} The resulting PMREM.
  18386. * @see {@link PMREMGenerator#fromEquirectangularAsync}
  18387. */
  18388. fromEquirectangular( equirectangular, renderTarget = null ) {
  18389. if ( this._hasInitialized === false ) {
  18390. throw new Error( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Use "await renderer.init();" before using this method.' );
  18391. }
  18392. return this._fromTexture( equirectangular, renderTarget );
  18393. }
  18394. /**
  18395. * Generates a PMREM from an equirectangular texture, which can be either LDR
  18396. * or HDR. The ideal input image size is 1k (1024 x 512),
  18397. * as this matches best with the 256 x 256 cubemap output.
  18398. *
  18399. * @deprecated
  18400. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  18401. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  18402. * @return {Promise<RenderTarget>} The resulting PMREM.
  18403. * @see {@link PMREMGenerator#fromEquirectangular}
  18404. */
  18405. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  18406. warnOnce( 'PMREMGenerator: ".fromEquirectangularAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  18407. await this._renderer.init();
  18408. return this._fromTexture( equirectangular, renderTarget );
  18409. }
  18410. /**
  18411. * Generates a PMREM from an cubemap texture, which can be either LDR
  18412. * or HDR. The ideal input cube size is 256 x 256, as this matches best
  18413. * with the 256 x 256 cubemap output. The minimum supported input cube
  18414. * size is 16 x 16 per face.
  18415. *
  18416. * @param {Texture} cubemap - The cubemap texture to be converted.
  18417. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  18418. * @return {RenderTarget} The resulting PMREM.
  18419. * @see {@link PMREMGenerator#fromCubemapAsync}
  18420. */
  18421. fromCubemap( cubemap, renderTarget = null ) {
  18422. if ( this._hasInitialized === false ) {
  18423. throw new Error( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Use "await renderer.init();" before using this method.' );
  18424. }
  18425. return this._fromTexture( cubemap, renderTarget );
  18426. }
  18427. /**
  18428. * Generates a PMREM from an cubemap texture, which can be either LDR
  18429. * or HDR. The ideal input cube size is 256 x 256,
  18430. * with the 256 x 256 cubemap output.
  18431. *
  18432. * @deprecated
  18433. * @param {Texture} cubemap - The cubemap texture to be converted.
  18434. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  18435. * @return {Promise<RenderTarget>} The resulting PMREM.
  18436. * @see {@link PMREMGenerator#fromCubemap}
  18437. */
  18438. async fromCubemapAsync( cubemap, renderTarget = null ) {
  18439. warnOnce( 'PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  18440. await this._renderer.init();
  18441. return this._fromTexture( cubemap, renderTarget );
  18442. }
  18443. /**
  18444. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  18445. * your texture's network fetch for increased concurrency.
  18446. *
  18447. * @returns {Promise}
  18448. */
  18449. async compileCubemapShader() {
  18450. if ( this._cubemapMaterial === null ) {
  18451. this._cubemapMaterial = _getCubemapMaterial();
  18452. await this._compileMaterial( this._cubemapMaterial );
  18453. }
  18454. }
  18455. /**
  18456. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  18457. * your texture's network fetch for increased concurrency.
  18458. *
  18459. * @returns {Promise}
  18460. */
  18461. async compileEquirectangularShader() {
  18462. if ( this._equirectMaterial === null ) {
  18463. this._equirectMaterial = _getEquirectMaterial();
  18464. await this._compileMaterial( this._equirectMaterial );
  18465. }
  18466. }
  18467. /**
  18468. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  18469. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  18470. * one of them will cause any others to also become unusable.
  18471. */
  18472. dispose() {
  18473. this._dispose();
  18474. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  18475. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  18476. if ( this._backgroundBox !== null ) {
  18477. this._backgroundBox.geometry.dispose();
  18478. this._backgroundBox.material.dispose();
  18479. }
  18480. }
  18481. // private interface
  18482. _setSizeFromTexture( texture ) {
  18483. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  18484. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  18485. } else { // Equirectangular
  18486. this._setSize( texture.image.width / 4 );
  18487. }
  18488. }
  18489. _setSize( cubeSize ) {
  18490. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  18491. this._cubeSize = Math.pow( 2, this._lodMax );
  18492. }
  18493. _dispose() {
  18494. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  18495. if ( this._ggxMaterial !== null ) this._ggxMaterial.dispose();
  18496. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  18497. for ( let i = 0; i < this._lodMeshes.length; i ++ ) {
  18498. this._lodMeshes[ i ].geometry.dispose();
  18499. }
  18500. }
  18501. _cleanup( outputTarget ) {
  18502. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  18503. outputTarget.scissorTest = false;
  18504. this._setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  18505. }
  18506. _fromTexture( texture, renderTarget ) {
  18507. this._setSizeFromTexture( texture );
  18508. _oldTarget = this._renderer.getRenderTarget();
  18509. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  18510. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  18511. const cubeUVRenderTarget = renderTarget || this._allocateTarget( false );
  18512. this._init( cubeUVRenderTarget );
  18513. this._textureToCubeUV( texture, cubeUVRenderTarget );
  18514. this._applyPMREM( cubeUVRenderTarget );
  18515. this._cleanup( cubeUVRenderTarget );
  18516. return cubeUVRenderTarget;
  18517. }
  18518. _allocateTarget( depthBuffer ) {
  18519. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  18520. const height = 4 * this._cubeSize;
  18521. const cubeUVRenderTarget = _createRenderTarget( width, height, depthBuffer );
  18522. return cubeUVRenderTarget;
  18523. }
  18524. _init( renderTarget ) {
  18525. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== renderTarget.width || this._pingPongRenderTarget.height !== renderTarget.height ) {
  18526. if ( this._pingPongRenderTarget !== null ) {
  18527. this._dispose();
  18528. }
  18529. this._pingPongRenderTarget = _createRenderTarget( renderTarget.width, renderTarget.height );
  18530. const { _lodMax } = this;
  18531. ( { lodMeshes: this._lodMeshes, sizeLods: this._sizeLods } = _createPlanes( _lodMax ) );
  18532. this._blurMaterial = _getBlurShader( _lodMax, renderTarget.width, renderTarget.height );
  18533. this._ggxMaterial = _getGGXShader( _lodMax, renderTarget.width, renderTarget.height );
  18534. }
  18535. }
  18536. async _compileMaterial( material ) {
  18537. const mesh = new Mesh( new BufferGeometry(), material );
  18538. await this._renderer.compile( mesh, _flatCamera );
  18539. }
  18540. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  18541. const cubeCamera = _cubeCamera;
  18542. cubeCamera.near = near;
  18543. cubeCamera.far = far;
  18544. // px, py, pz, nx, ny, nz
  18545. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  18546. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  18547. const renderer = this._renderer;
  18548. const originalAutoClear = renderer.autoClear;
  18549. renderer.getClearColor( _clearColor$2 );
  18550. renderer.autoClear = false;
  18551. if ( this._backgroundBox === null ) {
  18552. this._backgroundBox = new Mesh(
  18553. new BoxGeometry(),
  18554. new MeshBasicMaterial( {
  18555. name: 'PMREM.Background',
  18556. side: BackSide,
  18557. depthWrite: false,
  18558. depthTest: false,
  18559. } )
  18560. );
  18561. }
  18562. const backgroundBox = this._backgroundBox;
  18563. const backgroundMaterial = backgroundBox.material;
  18564. let useSolidColor = false;
  18565. const background = scene.background;
  18566. if ( background ) {
  18567. if ( background.isColor ) {
  18568. backgroundMaterial.color.copy( background );
  18569. scene.background = null;
  18570. useSolidColor = true;
  18571. }
  18572. } else {
  18573. backgroundMaterial.color.copy( _clearColor$2 );
  18574. useSolidColor = true;
  18575. }
  18576. renderer.setRenderTarget( cubeUVRenderTarget );
  18577. renderer.clear();
  18578. if ( useSolidColor ) {
  18579. renderer.render( backgroundBox, cubeCamera );
  18580. }
  18581. for ( let i = 0; i < 6; i ++ ) {
  18582. const col = i % 3;
  18583. if ( col === 0 ) {
  18584. cubeCamera.up.set( 0, upSign[ i ], 0 );
  18585. cubeCamera.position.set( position.x, position.y, position.z );
  18586. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  18587. } else if ( col === 1 ) {
  18588. cubeCamera.up.set( 0, 0, upSign[ i ] );
  18589. cubeCamera.position.set( position.x, position.y, position.z );
  18590. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  18591. } else {
  18592. cubeCamera.up.set( 0, upSign[ i ], 0 );
  18593. cubeCamera.position.set( position.x, position.y, position.z );
  18594. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  18595. }
  18596. const size = this._cubeSize;
  18597. this._setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  18598. renderer.render( scene, cubeCamera );
  18599. }
  18600. renderer.autoClear = originalAutoClear;
  18601. scene.background = background;
  18602. }
  18603. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  18604. const renderer = this._renderer;
  18605. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  18606. if ( isCubeTexture ) {
  18607. if ( this._cubemapMaterial === null ) {
  18608. this._cubemapMaterial = _getCubemapMaterial( texture );
  18609. }
  18610. } else {
  18611. if ( this._equirectMaterial === null ) {
  18612. this._equirectMaterial = _getEquirectMaterial( texture );
  18613. }
  18614. }
  18615. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  18616. material.fragmentNode.value = texture;
  18617. const mesh = this._lodMeshes[ 0 ];
  18618. mesh.material = material;
  18619. const size = this._cubeSize;
  18620. this._setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  18621. renderer.setRenderTarget( cubeUVRenderTarget );
  18622. renderer.render( mesh, _flatCamera );
  18623. }
  18624. _applyPMREM( cubeUVRenderTarget ) {
  18625. const renderer = this._renderer;
  18626. const autoClear = renderer.autoClear;
  18627. renderer.autoClear = false;
  18628. const n = this._lodMeshes.length;
  18629. // Use GGX VNDF importance sampling
  18630. for ( let i = 1; i < n; i ++ ) {
  18631. this._applyGGXFilter( cubeUVRenderTarget, i - 1, i );
  18632. }
  18633. renderer.autoClear = autoClear;
  18634. }
  18635. /**
  18636. * Applies GGX VNDF importance sampling filter to generate a prefiltered environment map.
  18637. * Uses Monte Carlo integration with VNDF importance sampling to accurately represent the
  18638. * GGX BRDF for physically-based rendering. Reads from the previous LOD level and
  18639. * applies incremental roughness filtering to avoid over-blurring.
  18640. *
  18641. * @private
  18642. * @param {RenderTarget} cubeUVRenderTarget
  18643. * @param {number} lodIn - Source LOD level to read from
  18644. * @param {number} lodOut - Target LOD level to write to
  18645. */
  18646. _applyGGXFilter( cubeUVRenderTarget, lodIn, lodOut ) {
  18647. const renderer = this._renderer;
  18648. const pingPongRenderTarget = this._pingPongRenderTarget;
  18649. const ggxMaterial = this._ggxMaterial;
  18650. const ggxMesh = this._lodMeshes[ lodOut ];
  18651. ggxMesh.material = ggxMaterial;
  18652. const ggxUniforms = _uniformsMap.get( ggxMaterial );
  18653. // Calculate incremental roughness between LOD levels
  18654. const targetRoughness = lodOut / ( this._lodMeshes.length - 1 );
  18655. const sourceRoughness = lodIn / ( this._lodMeshes.length - 1 );
  18656. const incrementalRoughness = Math.sqrt( targetRoughness * targetRoughness - sourceRoughness * sourceRoughness );
  18657. // Apply blur strength mapping for better quality across the roughness range
  18658. const blurStrength = targetRoughness * 1.25;
  18659. const adjustedRoughness = incrementalRoughness * blurStrength;
  18660. // Calculate viewport position based on output LOD level
  18661. const { _lodMax } = this;
  18662. const outputSize = this._sizeLods[ lodOut ];
  18663. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  18664. const y = 4 * ( this._cubeSize - outputSize );
  18665. // Read from previous LOD with incremental roughness
  18666. cubeUVRenderTarget.texture.frame = ( cubeUVRenderTarget.texture.frame || 0 ) + 1;
  18667. ggxUniforms.envMap.value = cubeUVRenderTarget.texture;
  18668. ggxUniforms.roughness.value = adjustedRoughness;
  18669. ggxUniforms.mipInt.value = _lodMax - lodIn; // Sample from input LOD
  18670. this._setViewport( pingPongRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  18671. renderer.setRenderTarget( pingPongRenderTarget );
  18672. renderer.render( ggxMesh, _flatCamera );
  18673. // Copy from pingPong back to cubeUV (simple direct copy)
  18674. pingPongRenderTarget.texture.frame = ( pingPongRenderTarget.texture.frame || 0 ) + 1;
  18675. ggxUniforms.envMap.value = pingPongRenderTarget.texture;
  18676. ggxUniforms.roughness.value = 0.0; // Direct copy
  18677. ggxUniforms.mipInt.value = _lodMax - lodOut; // Read from the level we just wrote
  18678. this._setViewport( cubeUVRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  18679. renderer.setRenderTarget( cubeUVRenderTarget );
  18680. renderer.render( ggxMesh, _flatCamera );
  18681. }
  18682. /**
  18683. * This is a two-pass Gaussian blur for a cubemap. Each pass importance-samples
  18684. * the Gaussian along a spiral kernel (Golden Angle), which distributes samples
  18685. * isotropically on the sphere (no pole artifacts).
  18686. *
  18687. * Used for initial scene blur in fromScene() method when sigma > 0.
  18688. *
  18689. * @private
  18690. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  18691. * @param {number} lodIn - The input level-of-detail.
  18692. * @param {number} lodOut - The output level-of-detail.
  18693. * @param {number} sigma - The blur radius in radians.
  18694. */
  18695. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma ) {
  18696. const pingPongRenderTarget = this._pingPongRenderTarget;
  18697. // Two passes of sigma / sqrt( 2 ) compose to a blur of sigma while squaring
  18698. // the effective sample count. Sigmas beyond PI are visually indistinguishable
  18699. // from a uniform blur, so clamp to keep the shader math finite.
  18700. const blurSigma = Math.min( sigma, Math.PI ) / Math.SQRT2;
  18701. this._blurPass( cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, blurSigma );
  18702. this._blurPass( pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, blurSigma );
  18703. }
  18704. _blurPass( targetIn, targetOut, lodIn, lodOut, sigmaRadians ) {
  18705. const renderer = this._renderer;
  18706. const blurMaterial = this._blurMaterial;
  18707. const blurMesh = this._lodMeshes[ lodOut ];
  18708. blurMesh.material = blurMaterial;
  18709. const blurUniforms = _uniformsMap.get( blurMaterial );
  18710. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  18711. blurUniforms.envMap.value = targetIn.texture;
  18712. blurUniforms.sigma.value = sigmaRadians;
  18713. blurUniforms.mipInt.value = this._lodMax - lodIn;
  18714. const outputSize = this._sizeLods[ lodOut ];
  18715. const x = 3 * outputSize * ( lodOut > this._lodMax - LOD_MIN ? lodOut - this._lodMax + LOD_MIN : 0 );
  18716. const y = 4 * ( this._cubeSize - outputSize );
  18717. this._setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  18718. renderer.setRenderTarget( targetOut );
  18719. renderer.render( blurMesh, _flatCamera );
  18720. }
  18721. _setViewport( target, x, y, width, height ) {
  18722. if ( this._renderer.isWebGLRenderer ) {
  18723. target.viewport.set( x, target.height - height - y, width, height );
  18724. target.scissor.set( x, target.height - height - y, width, height );
  18725. } else {
  18726. target.viewport.set( x, y, width, height );
  18727. target.scissor.set( x, y, width, height );
  18728. }
  18729. }
  18730. }
  18731. function _createPlanes( lodMax ) {
  18732. const sizeLods = [];
  18733. const lodMeshes = [];
  18734. let lod = lodMax;
  18735. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LODS;
  18736. for ( let i = 0; i < totalLods; i ++ ) {
  18737. const sizeLod = Math.pow( 2, lod );
  18738. sizeLods.push( sizeLod );
  18739. // UVs overshoot the face by one texel to bake the CubeUV border into the directions.
  18740. const texelSize = 1.0 / ( sizeLod - 2 );
  18741. const min = - texelSize;
  18742. const max = 1 + texelSize;
  18743. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  18744. const cubeFaces = 6;
  18745. const vertices = 6;
  18746. const positionSize = 3;
  18747. const position = new Float32Array( positionSize * vertices * cubeFaces );
  18748. const outputDirection = new Float32Array( positionSize * vertices * cubeFaces );
  18749. for ( let face = 0; face < cubeFaces; face ++ ) {
  18750. const x = ( face % 3 ) * 2 / 3 - 1;
  18751. const y = face > 2 ? 0 : -1;
  18752. const coordinates = [
  18753. x, y, 0,
  18754. x + 2 / 3, y, 0,
  18755. x + 2 / 3, y + 1, 0,
  18756. x, y, 0,
  18757. x + 2 / 3, y + 1, 0,
  18758. x, y + 1, 0
  18759. ];
  18760. const faceIdx = _faceLib[ face ];
  18761. position.set( coordinates, positionSize * vertices * faceIdx );
  18762. for ( let vertex = 0; vertex < vertices; vertex ++ ) {
  18763. const u = uv1[ vertex * 2 ] * 2 - 1;
  18764. const v = uv1[ vertex * 2 + 1 ] * 2 - 1;
  18765. // RH coordinate system; PMREM face-indexing convention
  18766. if ( faceIdx === 0 ) {
  18767. _direction.set( 1, v, u ); // pos x
  18768. } else if ( faceIdx === 1 ) {
  18769. _direction.set( - u, 1, - v ); // pos y
  18770. } else if ( faceIdx === 2 ) {
  18771. _direction.set( - u, v, 1 ); // pos z
  18772. } else if ( faceIdx === 3 ) {
  18773. _direction.set( -1, v, - u ); // neg x
  18774. } else if ( faceIdx === 4 ) {
  18775. _direction.set( - u, -1, v ); // neg y
  18776. } else {
  18777. _direction.set( u, v, -1 ); // neg z
  18778. }
  18779. _direction.toArray( outputDirection, ( faceIdx * vertices + vertex ) * positionSize );
  18780. }
  18781. }
  18782. const planes = new BufferGeometry();
  18783. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  18784. planes.setAttribute( 'outputDirection', new BufferAttribute( outputDirection, positionSize ) );
  18785. lodMeshes.push( new Mesh( planes, null ) );
  18786. if ( lod > LOD_MIN ) {
  18787. lod --;
  18788. }
  18789. }
  18790. return { lodMeshes, sizeLods };
  18791. }
  18792. function _createRenderTarget( width, height, depthBuffer ) {
  18793. const params = {
  18794. magFilter: LinearFilter,
  18795. minFilter: LinearFilter,
  18796. generateMipmaps: false,
  18797. type: HalfFloatType,
  18798. format: RGBAFormat,
  18799. colorSpace: LinearSRGBColorSpace,
  18800. depthBuffer
  18801. };
  18802. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  18803. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  18804. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  18805. cubeUVRenderTarget.texture.isPMREMTexture = true;
  18806. cubeUVRenderTarget.scissorTest = true;
  18807. return cubeUVRenderTarget;
  18808. }
  18809. function _getMaterial( type ) {
  18810. const material = new NodeMaterial();
  18811. material.depthTest = false;
  18812. material.depthWrite = false;
  18813. material.blending = NoBlending;
  18814. material.name = `PMREM_${ type }`;
  18815. return material;
  18816. }
  18817. function _getBlurShader( lodMax, width, height ) {
  18818. const envMap = texture();
  18819. const sigma = uniform( 0 );
  18820. const mipInt = uniform( 0 ); // int
  18821. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  18822. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  18823. const CUBEUV_MAX_MIP = float( lodMax );
  18824. const materialUniforms = {
  18825. envMap,
  18826. sigma,
  18827. mipInt,
  18828. CUBEUV_TEXEL_WIDTH,
  18829. CUBEUV_TEXEL_HEIGHT,
  18830. CUBEUV_MAX_MIP
  18831. };
  18832. const material = _getMaterial( 'blur' );
  18833. material.fragmentNode = sphericalGaussianBlur( {
  18834. ...materialUniforms,
  18835. outputDirection: _outputDirection,
  18836. SAMPLES: int( BLUR_SAMPLES )
  18837. } );
  18838. _uniformsMap.set( material, materialUniforms );
  18839. return material;
  18840. }
  18841. function _getGGXShader( lodMax, width, height ) {
  18842. const envMap = texture();
  18843. const roughness = uniform( 0 );
  18844. const mipInt = uniform( 0 );
  18845. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  18846. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  18847. const CUBEUV_MAX_MIP = float( lodMax );
  18848. const materialUniforms = {
  18849. envMap,
  18850. roughness,
  18851. mipInt,
  18852. CUBEUV_TEXEL_WIDTH,
  18853. CUBEUV_TEXEL_HEIGHT,
  18854. CUBEUV_MAX_MIP
  18855. };
  18856. const material = _getMaterial( 'ggx' );
  18857. material.fragmentNode = ggxConvolution( {
  18858. ...materialUniforms,
  18859. N_immutable: _outputDirection,
  18860. GGX_SAMPLES: uint( GGX_SAMPLES )
  18861. } );
  18862. _uniformsMap.set( material, materialUniforms );
  18863. return material;
  18864. }
  18865. function _getCubemapMaterial( envTexture ) {
  18866. const material = _getMaterial( 'cubemap' );
  18867. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  18868. return material;
  18869. }
  18870. function _getEquirectMaterial( envTexture ) {
  18871. const material = _getMaterial( 'equirect' );
  18872. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  18873. return material;
  18874. }
  18875. const _cache = new WeakMap();
  18876. /**
  18877. * Generates the cubeUV size based on the given image height.
  18878. *
  18879. * @private
  18880. * @param {number} imageHeight - The image height.
  18881. * @return {{texelWidth: number,texelHeight: number, maxMip: number}} The result object.
  18882. */
  18883. function _generateCubeUVSize( imageHeight ) {
  18884. const maxMip = Math.log2( imageHeight ) - 2;
  18885. const texelHeight = 1.0 / imageHeight;
  18886. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  18887. return { texelWidth, texelHeight, maxMip };
  18888. }
  18889. /**
  18890. * Generates a PMREM from the given texture.
  18891. *
  18892. * @private
  18893. * @param {Texture} texture - The texture to create the PMREM for.
  18894. * @param {Renderer} renderer - The renderer.
  18895. * @param {PMREMGenerator} generator - The PMREM generator.
  18896. * @return {?Texture} The PMREM.
  18897. */
  18898. function _getPMREMFromTexture( texture, renderer, generator ) {
  18899. const cache = _getCache( renderer );
  18900. let cacheTexture = cache.get( texture );
  18901. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  18902. if ( pmremVersion !== texture.pmremVersion ) {
  18903. const image = texture.image;
  18904. if ( texture.isCubeTexture ) {
  18905. if ( isCubeMapReady( image ) ) {
  18906. cacheTexture = generator.fromCubemap( texture, cacheTexture );
  18907. } else {
  18908. return null;
  18909. }
  18910. } else {
  18911. if ( isEquirectangularMapReady( image ) ) {
  18912. cacheTexture = generator.fromEquirectangular( texture, cacheTexture );
  18913. } else {
  18914. return null;
  18915. }
  18916. }
  18917. cacheTexture.pmremVersion = texture.pmremVersion;
  18918. // add dispose event listener for new PMREMs
  18919. if ( cache.has( texture ) === false ) {
  18920. const onDispose = () => {
  18921. texture.removeEventListener( 'dispose', onDispose );
  18922. const pmrem = cache.get( texture );
  18923. if ( pmrem !== undefined ) {
  18924. pmrem.dispose();
  18925. cache.delete( texture );
  18926. }
  18927. };
  18928. texture.addEventListener( 'dispose', onDispose );
  18929. }
  18930. //
  18931. cache.set( texture, cacheTexture );
  18932. }
  18933. return cacheTexture.texture;
  18934. }
  18935. /**
  18936. * Returns a cache that stores generated PMREMs for the respective textures.
  18937. * A cache must be maintained per renderer since PMREMs are render target textures
  18938. * which can't be shared across render contexts.
  18939. *
  18940. * @private
  18941. * @param {Renderer} renderer - The renderer.
  18942. * @return {WeakMap<Texture, Texture>} The PMREM cache.
  18943. */
  18944. function _getCache( renderer ) {
  18945. let rendererCache = _cache.get( renderer );
  18946. if ( rendererCache === undefined ) {
  18947. rendererCache = new WeakMap();
  18948. _cache.set( renderer, rendererCache );
  18949. }
  18950. return rendererCache;
  18951. }
  18952. /**
  18953. * This node represents a PMREM which is a special type of preprocessed
  18954. * environment map intended for PBR materials.
  18955. *
  18956. * ```js
  18957. * const material = new MeshStandardNodeMaterial();
  18958. * material.envNode = pmremTexture( envMap );
  18959. * ```
  18960. *
  18961. * @augments TempNode
  18962. */
  18963. class PMREMNode extends TempNode {
  18964. static get type() {
  18965. return 'PMREMNode';
  18966. }
  18967. /**
  18968. * Constructs a new function overloading node.
  18969. *
  18970. * @param {Texture} value - The input texture.
  18971. * @param {Node<vec2>} [uvNode=null] - The uv node.
  18972. * @param {Node<float>} [levelNode=null] - The level node.
  18973. */
  18974. constructor( value, uvNode = null, levelNode = null ) {
  18975. super( 'vec3' );
  18976. /**
  18977. * Reference to the input texture.
  18978. *
  18979. * @private
  18980. * @type {Texture}
  18981. */
  18982. this._value = value;
  18983. /**
  18984. * Reference to the generated PMREM.
  18985. *
  18986. * @private
  18987. * @type {Texture | null}
  18988. * @default null
  18989. */
  18990. this._pmrem = null;
  18991. /**
  18992. * The uv node.
  18993. *
  18994. * @type {Node<vec2>}
  18995. */
  18996. this.uvNode = uvNode;
  18997. /**
  18998. * The level node.
  18999. *
  19000. * @type {Node<float>}
  19001. */
  19002. this.levelNode = levelNode;
  19003. /**
  19004. * Reference to a PMREM generator.
  19005. *
  19006. * @private
  19007. * @type {?PMREMGenerator}
  19008. * @default null
  19009. */
  19010. this._generator = null;
  19011. const defaultTexture = new Texture();
  19012. defaultTexture.isRenderTargetTexture = true;
  19013. /**
  19014. * The texture node holding the generated PMREM.
  19015. *
  19016. * @private
  19017. * @type {TextureNode}
  19018. */
  19019. this._texture = texture( defaultTexture );
  19020. /**
  19021. * A uniform representing the PMREM's width.
  19022. *
  19023. * @private
  19024. * @type {UniformNode<float>}
  19025. */
  19026. this._width = uniform( 0 );
  19027. /**
  19028. * A uniform representing the PMREM's height.
  19029. *
  19030. * @private
  19031. * @type {UniformNode<float>}
  19032. */
  19033. this._height = uniform( 0 );
  19034. /**
  19035. * A uniform representing the PMREM's max Mip.
  19036. *
  19037. * @private
  19038. * @type {UniformNode<float>}
  19039. */
  19040. this._maxMip = uniform( 0 );
  19041. /**
  19042. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  19043. *
  19044. * @type {string}
  19045. * @default 'render'
  19046. */
  19047. this.updateBeforeType = NodeUpdateType.RENDER;
  19048. }
  19049. set value( value ) {
  19050. this._value = value;
  19051. this._pmrem = null;
  19052. }
  19053. /**
  19054. * The node's texture value.
  19055. *
  19056. * @type {Texture}
  19057. */
  19058. get value() {
  19059. return this._value;
  19060. }
  19061. /**
  19062. * Uses the given PMREM texture to update internal values.
  19063. *
  19064. * @param {Texture} texture - The PMREM texture.
  19065. */
  19066. updateFromTexture( texture ) {
  19067. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  19068. this._texture.value = texture;
  19069. this._width.value = cubeUVSize.texelWidth;
  19070. this._height.value = cubeUVSize.texelHeight;
  19071. this._maxMip.value = cubeUVSize.maxMip;
  19072. }
  19073. updateBefore( frame ) {
  19074. let pmrem = this._pmrem;
  19075. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  19076. const texture = this._value;
  19077. if ( pmremVersion !== texture.pmremVersion ) {
  19078. if ( texture.isPMREMTexture === true || texture.mapping === CubeUVReflectionMapping ) {
  19079. pmrem = texture;
  19080. } else {
  19081. pmrem = _getPMREMFromTexture( texture, frame.renderer, this._generator );
  19082. }
  19083. if ( pmrem !== null ) {
  19084. this._pmrem = pmrem;
  19085. this.updateFromTexture( pmrem );
  19086. }
  19087. }
  19088. }
  19089. setup( builder ) {
  19090. if ( this._generator === null ) {
  19091. this._generator = new PMREMGenerator( builder.renderer );
  19092. }
  19093. this.updateBefore( builder );
  19094. //
  19095. let uvNode = this.uvNode;
  19096. if ( uvNode === null && builder.context.getUV ) {
  19097. uvNode = builder.context.getUV( this, builder );
  19098. }
  19099. //
  19100. // PMREMGenerator renders into a render target with inverted Y, so its output needs the Y
  19101. // flip on sampling. Externally authored PMREMs follow the standard convention and don't.
  19102. uvNode = this._pmrem === null || this._pmrem.isRenderTargetTexture
  19103. ? materialEnvRotation.mul( vec3( uvNode.x, uvNode.y.negate(), uvNode.z ) )
  19104. : materialEnvRotation.mul( uvNode );
  19105. //
  19106. let levelNode = this.levelNode;
  19107. if ( levelNode === null && builder.context.getTextureLevel ) {
  19108. levelNode = builder.context.getTextureLevel( this );
  19109. }
  19110. //
  19111. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  19112. }
  19113. dispose() {
  19114. super.dispose();
  19115. if ( this._generator !== null ) this._generator.dispose();
  19116. }
  19117. }
  19118. /**
  19119. * Returns `true` if the given cube map image has been fully loaded.
  19120. *
  19121. * @private
  19122. * @param {?Array<(Image|Object)>} [image] - The cube map image.
  19123. * @return {boolean} Whether the given cube map is ready or not.
  19124. */
  19125. function isCubeMapReady( image ) {
  19126. if ( image === null || image === undefined ) return false;
  19127. let count = 0;
  19128. const length = 6;
  19129. for ( let i = 0; i < length; i ++ ) {
  19130. if ( image[ i ] !== undefined ) count ++;
  19131. }
  19132. return count === length;
  19133. }
  19134. /**
  19135. * Returns `true` if the given equirectangular image has been fully loaded.
  19136. *
  19137. * @private
  19138. * @param {(Image|Object)} image - The equirectangular image.
  19139. * @return {boolean} Whether the given cube map is ready or not.
  19140. */
  19141. function isEquirectangularMapReady( image ) {
  19142. if ( image === null || image === undefined ) return false;
  19143. return image.height > 0;
  19144. }
  19145. /**
  19146. * TSL function for creating a PMREM node.
  19147. *
  19148. * @tsl
  19149. * @function
  19150. * @param {Texture} value - The input texture.
  19151. * @param {?Node<vec2>} [uvNode=null] - The uv node.
  19152. * @param {?Node<float>} [levelNode=null] - The level node.
  19153. * @returns {PMREMNode}
  19154. */
  19155. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode ).setParameterLength( 1, 3 );
  19156. const _rendererCache = new WeakMap();
  19157. /**
  19158. * Represents a physical model for Image-based lighting (IBL). The environment
  19159. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  19160. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  19161. *
  19162. * @augments LightingNode
  19163. */
  19164. class EnvironmentNode extends LightingNode {
  19165. static get type() {
  19166. return 'EnvironmentNode';
  19167. }
  19168. /**
  19169. * Constructs a new environment node.
  19170. *
  19171. * @param {Node} [envNode=null] - A node representing the environment.
  19172. */
  19173. constructor( envNode = null ) {
  19174. super();
  19175. /**
  19176. * A node representing the environment.
  19177. *
  19178. * @type {?Node}
  19179. * @default null
  19180. */
  19181. this.envNode = envNode;
  19182. }
  19183. setup( builder ) {
  19184. const { material } = builder;
  19185. let envNode = this.envNode;
  19186. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  19187. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  19188. const cache = this._getPMREMNodeCache( builder.renderer );
  19189. let cacheEnvNode = cache.get( value );
  19190. if ( cacheEnvNode === undefined ) {
  19191. cacheEnvNode = pmremTexture( value );
  19192. cache.set( value, cacheEnvNode );
  19193. }
  19194. envNode = cacheEnvNode;
  19195. }
  19196. //
  19197. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  19198. const radianceNormalView = useAnisotropy ? bentNormalView : normalView;
  19199. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( materialEnvIntensity );
  19200. const irradiance = envNode.context( createIrradianceContext( normalWorld ) ).mul( Math.PI ).mul( materialEnvIntensity );
  19201. const isolateRadiance = isolate( radiance );
  19202. const isolateIrradiance = isolate( irradiance );
  19203. //
  19204. builder.context.radiance.addAssign( isolateRadiance );
  19205. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  19206. //
  19207. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  19208. if ( clearcoatRadiance ) {
  19209. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, clearcoatNormalView ) ).mul( materialEnvIntensity );
  19210. const isolateClearcoatRadiance = isolate( clearcoatRadianceContext );
  19211. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  19212. }
  19213. }
  19214. /**
  19215. * Returns the PMREM node cache of the current renderer.
  19216. *
  19217. * @private
  19218. * @param {Renderer} renderer - The current renderer.
  19219. * @return {WeakMap} The node cache.
  19220. */
  19221. _getPMREMNodeCache( renderer ) {
  19222. let pmremCache = _rendererCache.get( renderer );
  19223. if ( pmremCache === undefined ) {
  19224. pmremCache = new WeakMap();
  19225. _rendererCache.set( renderer, pmremCache );
  19226. }
  19227. return pmremCache;
  19228. }
  19229. }
  19230. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  19231. let reflectVec = null;
  19232. return {
  19233. getUV: () => {
  19234. if ( reflectVec === null ) {
  19235. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  19236. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  19237. reflectVec = pow4( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  19238. reflectVec = reflectVec.transformDirection( cameraWorldMatrix );
  19239. }
  19240. return reflectVec;
  19241. },
  19242. getTextureLevel: () => {
  19243. return roughnessNode;
  19244. }
  19245. };
  19246. };
  19247. const createIrradianceContext = ( normalWorldNode ) => {
  19248. return {
  19249. getUV: () => {
  19250. return normalWorldNode;
  19251. },
  19252. getTextureLevel: () => {
  19253. return float( 1.0 );
  19254. }
  19255. };
  19256. };
  19257. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  19258. /**
  19259. * Node material version of {@link MeshStandardMaterial}.
  19260. *
  19261. * @augments NodeMaterial
  19262. */
  19263. class MeshStandardNodeMaterial extends NodeMaterial {
  19264. static get type() {
  19265. return 'MeshStandardNodeMaterial';
  19266. }
  19267. /**
  19268. * Constructs a new mesh standard node material.
  19269. *
  19270. * @param {Object} [parameters] - The configuration parameter.
  19271. */
  19272. constructor( parameters ) {
  19273. super();
  19274. /**
  19275. * This flag can be used for type testing.
  19276. *
  19277. * @type {boolean}
  19278. * @readonly
  19279. * @default true
  19280. */
  19281. this.isMeshStandardNodeMaterial = true;
  19282. /**
  19283. * Set to `true` because standard materials react on lights.
  19284. *
  19285. * @type {boolean}
  19286. * @default true
  19287. */
  19288. this.lights = true;
  19289. /**
  19290. * The emissive color of standard materials is by default inferred from the `emissive`,
  19291. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  19292. * overwrite the default and define the emissive color with a node instead.
  19293. *
  19294. * If you don't want to overwrite the emissive color but modify the existing
  19295. * value instead, use {@link materialEmissive}.
  19296. *
  19297. * @type {?Node<vec3>}
  19298. * @default null
  19299. */
  19300. this.emissiveNode = null;
  19301. /**
  19302. * The metalness of standard materials is by default inferred from the `metalness`,
  19303. * and `metalnessMap` properties. This node property allows to
  19304. * overwrite the default and define the metalness with a node instead.
  19305. *
  19306. * If you don't want to overwrite the metalness but modify the existing
  19307. * value instead, use {@link materialMetalness}.
  19308. *
  19309. * @type {?Node<float>}
  19310. * @default null
  19311. */
  19312. this.metalnessNode = null;
  19313. /**
  19314. * The roughness of standard materials is by default inferred from the `roughness`,
  19315. * and `roughnessMap` properties. This node property allows to
  19316. * overwrite the default and define the roughness with a node instead.
  19317. *
  19318. * If you don't want to overwrite the roughness but modify the existing
  19319. * value instead, use {@link materialRoughness}.
  19320. *
  19321. * @type {?Node<float>}
  19322. * @default null
  19323. */
  19324. this.roughnessNode = null;
  19325. this.setDefaultValues( _defaultValues$6 );
  19326. this.setValues( parameters );
  19327. }
  19328. /**
  19329. * Overwritten since this type of material uses {@link EnvironmentNode}
  19330. * to implement the PBR (PMREM based) environment mapping. Besides, the
  19331. * method honors `Scene.environment`.
  19332. *
  19333. * @param {NodeBuilder} builder - The current node builder.
  19334. * @return {?EnvironmentNode<vec3>} The environment node.
  19335. */
  19336. setupEnvironment( builder ) {
  19337. let envNode = super.setupEnvironment( builder );
  19338. if ( envNode === null && builder.environmentNode ) {
  19339. envNode = builder.environmentNode;
  19340. }
  19341. return envNode ? new EnvironmentNode( envNode ) : null;
  19342. }
  19343. /**
  19344. * Setups the lighting model.
  19345. *
  19346. * @return {PhysicalLightingModel} The lighting model.
  19347. */
  19348. setupLightingModel( /*builder*/ ) {
  19349. return new PhysicalLightingModel();
  19350. }
  19351. /**
  19352. * Setups the specular related node variables.
  19353. */
  19354. setupSpecular() {
  19355. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  19356. specularColor.assign( vec3( 0.04 ) );
  19357. specularColorBlended.assign( specularColorNode );
  19358. specularF90.assign( 1.0 );
  19359. }
  19360. /**
  19361. * Setups the standard specific node variables.
  19362. *
  19363. * @param {NodeBuilder} builder - The current node builder.
  19364. */
  19365. setupVariants() {
  19366. // METALNESS
  19367. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  19368. metalness.assign( metalnessNode );
  19369. // ROUGHNESS
  19370. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  19371. roughnessNode = getRoughness( { roughness: roughnessNode } );
  19372. roughness.assign( roughnessNode );
  19373. // SPECULAR COLOR
  19374. this.setupSpecular();
  19375. // DIFFUSE COLOR
  19376. diffuseContribution.assign( diffuseColor.rgb.mul( metalnessNode.oneMinus() ) );
  19377. }
  19378. }
  19379. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  19380. /**
  19381. * Node material version of {@link MeshPhysicalMaterial}.
  19382. *
  19383. * @augments MeshStandardNodeMaterial
  19384. */
  19385. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  19386. static get type() {
  19387. return 'MeshPhysicalNodeMaterial';
  19388. }
  19389. /**
  19390. * Constructs a new mesh physical node material.
  19391. *
  19392. * @param {Object} [parameters] - The configuration parameter.
  19393. */
  19394. constructor( parameters ) {
  19395. super();
  19396. /**
  19397. * This flag can be used for type testing.
  19398. *
  19399. * @type {boolean}
  19400. * @readonly
  19401. * @default true
  19402. */
  19403. this.isMeshPhysicalNodeMaterial = true;
  19404. /**
  19405. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  19406. * and `clearcoatMap` properties. This node property allows to overwrite the default
  19407. * and define the clearcoat with a node instead.
  19408. *
  19409. * If you don't want to overwrite the clearcoat but modify the existing
  19410. * value instead, use {@link materialClearcoat}.
  19411. *
  19412. * @type {?Node<float>}
  19413. * @default null
  19414. */
  19415. this.clearcoatNode = null;
  19416. /**
  19417. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  19418. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  19419. * and define the clearcoat roughness with a node instead.
  19420. *
  19421. * If you don't want to overwrite the clearcoat roughness but modify the existing
  19422. * value instead, use {@link materialClearcoatRoughness}.
  19423. *
  19424. * @type {?Node<float>}
  19425. * @default null
  19426. */
  19427. this.clearcoatRoughnessNode = null;
  19428. /**
  19429. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  19430. * property. This node property allows to overwrite the default
  19431. * and define the clearcoat normal with a node instead.
  19432. *
  19433. * If you don't want to overwrite the clearcoat normal but modify the existing
  19434. * value instead, use {@link materialClearcoatNormal}.
  19435. *
  19436. * @type {?Node<vec3>}
  19437. * @default null
  19438. */
  19439. this.clearcoatNormalNode = null;
  19440. /**
  19441. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  19442. * and `sheenColorMap` properties. This node property allows to overwrite the default
  19443. * and define the sheen with a node instead.
  19444. *
  19445. * If you don't want to overwrite the sheen but modify the existing
  19446. * value instead, use {@link materialSheen}.
  19447. *
  19448. * @type {?Node<vec3>}
  19449. * @default null
  19450. */
  19451. this.sheenNode = null;
  19452. /**
  19453. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  19454. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  19455. * and define the sheen roughness with a node instead.
  19456. *
  19457. * If you don't want to overwrite the sheen roughness but modify the existing
  19458. * value instead, use {@link materialSheenRoughness}.
  19459. *
  19460. * @type {?Node<float>}
  19461. * @default null
  19462. */
  19463. this.sheenRoughnessNode = null;
  19464. /**
  19465. * The iridescence of physical materials is by default inferred from the `iridescence`
  19466. * property. This node property allows to overwrite the default
  19467. * and define the iridescence with a node instead.
  19468. *
  19469. * If you don't want to overwrite the iridescence but modify the existing
  19470. * value instead, use {@link materialIridescence}.
  19471. *
  19472. * @type {?Node<float>}
  19473. * @default null
  19474. */
  19475. this.iridescenceNode = null;
  19476. /**
  19477. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  19478. * property. This node property allows to overwrite the default
  19479. * and define the iridescence IOR with a node instead.
  19480. *
  19481. * If you don't want to overwrite the iridescence IOR but modify the existing
  19482. * value instead, use {@link materialIridescenceIOR}.
  19483. *
  19484. * @type {?Node<float>}
  19485. * @default null
  19486. */
  19487. this.iridescenceIORNode = null;
  19488. /**
  19489. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  19490. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  19491. * and define the iridescence thickness with a node instead.
  19492. *
  19493. * If you don't want to overwrite the iridescence thickness but modify the existing
  19494. * value instead, use {@link materialIridescenceThickness}.
  19495. *
  19496. * @type {?Node<float>}
  19497. * @default null
  19498. */
  19499. this.iridescenceThicknessNode = null;
  19500. /**
  19501. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  19502. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  19503. * and define the specular intensity with a node instead.
  19504. *
  19505. * If you don't want to overwrite the specular intensity but modify the existing
  19506. * value instead, use {@link materialSpecularIntensity}.
  19507. *
  19508. * @type {?Node<float>}
  19509. * @default null
  19510. */
  19511. this.specularIntensityNode = null;
  19512. /**
  19513. * The specular color of physical materials is by default inferred from the `specularColor`
  19514. * and `specularColorMap` properties. This node property allows to overwrite the default
  19515. * and define the specular color with a node instead.
  19516. *
  19517. * If you don't want to overwrite the specular color but modify the existing
  19518. * value instead, use {@link materialSpecularColor}.
  19519. *
  19520. * @type {?Node<vec3>}
  19521. * @default null
  19522. */
  19523. this.specularColorNode = null;
  19524. /**
  19525. * The ior of physical materials is by default inferred from the `ior`
  19526. * property. This node property allows to overwrite the default
  19527. * and define the ior with a node instead.
  19528. *
  19529. * If you don't want to overwrite the ior but modify the existing
  19530. * value instead, use {@link materialIOR}.
  19531. *
  19532. * @type {?Node<float>}
  19533. * @default null
  19534. */
  19535. this.iorNode = null;
  19536. /**
  19537. * The transmission of physical materials is by default inferred from the `transmission` and
  19538. * `transmissionMap` properties. This node property allows to overwrite the default
  19539. * and define the transmission with a node instead.
  19540. *
  19541. * If you don't want to overwrite the transmission but modify the existing
  19542. * value instead, use {@link materialTransmission}.
  19543. *
  19544. * @type {?Node<float>}
  19545. * @default null
  19546. */
  19547. this.transmissionNode = null;
  19548. /**
  19549. * The thickness of physical materials is by default inferred from the `thickness` and
  19550. * `thicknessMap` properties. This node property allows to overwrite the default
  19551. * and define the thickness with a node instead.
  19552. *
  19553. * If you don't want to overwrite the thickness but modify the existing
  19554. * value instead, use {@link materialThickness}.
  19555. *
  19556. * @type {?Node<float>}
  19557. * @default null
  19558. */
  19559. this.thicknessNode = null;
  19560. /**
  19561. * The attenuation distance of physical materials is by default inferred from the
  19562. * `attenuationDistance` property. This node property allows to overwrite the default
  19563. * and define the attenuation distance with a node instead.
  19564. *
  19565. * If you don't want to overwrite the attenuation distance but modify the existing
  19566. * value instead, use {@link materialAttenuationDistance}.
  19567. *
  19568. * @type {?Node<float>}
  19569. * @default null
  19570. */
  19571. this.attenuationDistanceNode = null;
  19572. /**
  19573. * The attenuation color of physical materials is by default inferred from the
  19574. * `attenuationColor` property. This node property allows to overwrite the default
  19575. * and define the attenuation color with a node instead.
  19576. *
  19577. * If you don't want to overwrite the attenuation color but modify the existing
  19578. * value instead, use {@link materialAttenuationColor}.
  19579. *
  19580. * @type {?Node<vec3>}
  19581. * @default null
  19582. */
  19583. this.attenuationColorNode = null;
  19584. /**
  19585. * The dispersion of physical materials is by default inferred from the
  19586. * `dispersion` property. This node property allows to overwrite the default
  19587. * and define the dispersion with a node instead.
  19588. *
  19589. * If you don't want to overwrite the dispersion but modify the existing
  19590. * value instead, use {@link materialDispersion}.
  19591. *
  19592. * @type {?Node<float>}
  19593. * @default null
  19594. */
  19595. this.dispersionNode = null;
  19596. /**
  19597. * The retroreflective strength of physical materials is by default inferred from the
  19598. * `retroreflective` property. This node property allows to overwrite the default
  19599. * and define the retroreflective strength with a node instead.
  19600. *
  19601. * If you don't want to overwrite the retroreflective strength but modify the existing
  19602. * value instead, use {@link materialRetroreflective}.
  19603. *
  19604. * @type {?Node<float>}
  19605. * @default null
  19606. */
  19607. this.retroreflectiveNode = null;
  19608. /**
  19609. * The anisotropy of physical materials is by default inferred from the
  19610. * `anisotropy` property. This node property allows to overwrite the default
  19611. * and define the anisotropy with a node instead.
  19612. *
  19613. * If you don't want to overwrite the anisotropy but modify the existing
  19614. * value instead, use {@link materialAnisotropy}.
  19615. *
  19616. * @type {?Node<float>}
  19617. * @default null
  19618. */
  19619. this.anisotropyNode = null;
  19620. this.setDefaultValues( _defaultValues$5 );
  19621. this.setValues( parameters );
  19622. }
  19623. /**
  19624. * Whether the lighting model should use clearcoat or not.
  19625. *
  19626. * @type {boolean}
  19627. * @default true
  19628. */
  19629. get useClearcoat() {
  19630. return this.clearcoat > 0 || this.clearcoatNode !== null;
  19631. }
  19632. /**
  19633. * Whether the lighting model should use iridescence or not.
  19634. *
  19635. * @type {boolean}
  19636. * @default true
  19637. */
  19638. get useIridescence() {
  19639. return this.iridescence > 0 || this.iridescenceNode !== null;
  19640. }
  19641. /**
  19642. * Whether the lighting model should use sheen or not.
  19643. *
  19644. * @type {boolean}
  19645. * @default true
  19646. */
  19647. get useSheen() {
  19648. return this.sheen > 0 || this.sheenNode !== null;
  19649. }
  19650. /**
  19651. * Whether the lighting model should use anisotropy or not.
  19652. *
  19653. * @type {boolean}
  19654. * @default true
  19655. */
  19656. get useAnisotropy() {
  19657. return this.anisotropy > 0 || this.anisotropyNode !== null;
  19658. }
  19659. /**
  19660. * Whether the lighting model should use transmission or not.
  19661. *
  19662. * @type {boolean}
  19663. * @default true
  19664. */
  19665. get useTransmission() {
  19666. return this.transmission > 0 || this.transmissionNode !== null;
  19667. }
  19668. /**
  19669. * Whether the lighting model should use dispersion or not.
  19670. *
  19671. * @type {boolean}
  19672. * @default true
  19673. */
  19674. get useDispersion() {
  19675. return this.dispersion > 0 || this.dispersionNode !== null;
  19676. }
  19677. /**
  19678. * Whether the lighting model should use retroreflection or not.
  19679. *
  19680. * @type {boolean}
  19681. * @default true
  19682. */
  19683. get useRetroreflective() {
  19684. return this.retroreflective > 0 || this.retroreflectiveNode !== null;
  19685. }
  19686. /**
  19687. * Setups the specular related node variables.
  19688. */
  19689. setupSpecular() {
  19690. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  19691. ior.assign( iorNode );
  19692. specularColor.assign( min$1( pow2( ior.sub( 1.0 ).div( ior.add( 1.0 ) ) ).mul( materialSpecularColor ), vec3( 1.0 ) ).mul( materialSpecularIntensity ) );
  19693. specularColorBlended.assign( mix( specularColor, diffuseColor.rgb, metalness ) );
  19694. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  19695. }
  19696. /**
  19697. * Setups the lighting model.
  19698. *
  19699. * @return {PhysicalLightingModel} The lighting model.
  19700. */
  19701. setupLightingModel( /*builder*/ ) {
  19702. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useRetroreflective );
  19703. }
  19704. /**
  19705. * Setups the physical specific node variables.
  19706. *
  19707. * @param {NodeBuilder} builder - The current node builder.
  19708. */
  19709. setupVariants( builder ) {
  19710. super.setupVariants( builder );
  19711. // CLEARCOAT
  19712. if ( this.useClearcoat ) {
  19713. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  19714. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  19715. clearcoat.assign( clearcoatNode );
  19716. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  19717. }
  19718. // SHEEN
  19719. if ( this.useSheen ) {
  19720. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  19721. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  19722. sheen.assign( sheenNode );
  19723. sheenRoughness.assign( sheenRoughnessNode );
  19724. }
  19725. // RETROREFLECTIVE
  19726. if ( this.useRetroreflective ) {
  19727. const retroreflectiveNode = this.retroreflectiveNode ? float( this.retroreflectiveNode ) : materialRetroreflective;
  19728. retroreflective.assign( retroreflectiveNode );
  19729. }
  19730. // IRIDESCENCE
  19731. if ( this.useIridescence ) {
  19732. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  19733. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  19734. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  19735. iridescence.assign( iridescenceNode );
  19736. iridescenceIOR.assign( iridescenceIORNode );
  19737. iridescenceThickness.assign( iridescenceThicknessNode );
  19738. }
  19739. // ANISOTROPY
  19740. if ( this.useAnisotropy ) {
  19741. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  19742. anisotropy.assign( anisotropyV.length() );
  19743. If( anisotropy.equal( 0.0 ), () => {
  19744. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  19745. } ).Else( () => {
  19746. anisotropyV.divAssign( vec2( anisotropy ) );
  19747. anisotropy.assign( anisotropy.saturate() );
  19748. } );
  19749. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  19750. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  19751. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  19752. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  19753. }
  19754. // TRANSMISSION
  19755. if ( this.useTransmission ) {
  19756. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  19757. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  19758. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  19759. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  19760. transmission.assign( transmissionNode );
  19761. thickness.assign( thicknessNode );
  19762. attenuationDistance.assign( attenuationDistanceNode );
  19763. attenuationColor.assign( attenuationColorNode );
  19764. if ( this.useDispersion ) {
  19765. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  19766. dispersion.assign( dispersionNode );
  19767. }
  19768. }
  19769. }
  19770. /**
  19771. * Setups the clearcoat normal node.
  19772. *
  19773. * @return {Node<vec3>} The clearcoat normal.
  19774. */
  19775. setupClearcoatNormal() {
  19776. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  19777. }
  19778. setup( builder ) {
  19779. builder.context.setupClearcoatNormal = () => subBuild( this.setupClearcoatNormal( builder ), 'NORMAL', 'vec3' );
  19780. super.setup( builder );
  19781. }
  19782. }
  19783. /**
  19784. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  19785. *
  19786. * @augments PhysicalLightingModel
  19787. */
  19788. class SSSLightingModel extends PhysicalLightingModel {
  19789. /**
  19790. * Constructs a new physical lighting model.
  19791. *
  19792. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  19793. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  19794. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  19795. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  19796. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  19797. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  19798. * @param {boolean} [sss=false] - Whether SSS is supported or not.
  19799. */
  19800. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  19801. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  19802. /**
  19803. * Whether the lighting model should use SSS or not.
  19804. *
  19805. * @type {boolean}
  19806. * @default false
  19807. */
  19808. this.useSSS = sss;
  19809. }
  19810. /**
  19811. * Extends the default implementation with a SSS term.
  19812. *
  19813. * Reference: [Approximating Translucency for a Fast, Cheap and Convincing Subsurface Scattering Look](https://colinbarrebrisebois.com/2011/03/07/gdc-2011-approximating-translucency-for-a-fast-cheap-and-convincing-subsurface-scattering-look/)
  19814. *
  19815. * @param {Object} input - The input data.
  19816. * @param {NodeBuilder} builder - The current node builder.
  19817. */
  19818. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  19819. if ( this.useSSS === true ) {
  19820. const material = builder.material;
  19821. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  19822. const scatteringHalf = lightDirection.add( normalView.mul( thicknessDistortionNode ) ).normalize();
  19823. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  19824. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  19825. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  19826. }
  19827. super.direct( { lightDirection, lightColor, reflectedLight }, builder );
  19828. }
  19829. }
  19830. /**
  19831. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  19832. * that implements a Subsurface scattering (SSS) term.
  19833. *
  19834. * @augments MeshPhysicalNodeMaterial
  19835. */
  19836. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  19837. static get type() {
  19838. return 'MeshSSSNodeMaterial';
  19839. }
  19840. /**
  19841. * Constructs a new mesh SSS node material.
  19842. *
  19843. * @param {Object} [parameters] - The configuration parameter.
  19844. */
  19845. constructor( parameters ) {
  19846. super( parameters );
  19847. /**
  19848. * Represents the thickness color.
  19849. *
  19850. * @type {?Node<vec3>}
  19851. * @default null
  19852. */
  19853. this.thicknessColorNode = null;
  19854. /**
  19855. * Represents the distortion factor.
  19856. *
  19857. * @type {?Node<float>}
  19858. */
  19859. this.thicknessDistortionNode = float( 0.1 );
  19860. /**
  19861. * Represents the thickness ambient factor.
  19862. *
  19863. * @type {?Node<float>}
  19864. */
  19865. this.thicknessAmbientNode = float( 0.0 );
  19866. /**
  19867. * Represents the thickness attenuation.
  19868. *
  19869. * @type {?Node<float>}
  19870. */
  19871. this.thicknessAttenuationNode = float( .1 );
  19872. /**
  19873. * Represents the thickness power.
  19874. *
  19875. * @type {?Node<float>}
  19876. */
  19877. this.thicknessPowerNode = float( 2.0 );
  19878. /**
  19879. * Represents the thickness scale.
  19880. *
  19881. * @type {?Node<float>}
  19882. */
  19883. this.thicknessScaleNode = float( 10.0 );
  19884. }
  19885. /**
  19886. * Whether the lighting model should use SSS or not.
  19887. *
  19888. * @type {boolean}
  19889. * @default true
  19890. */
  19891. get useSSS() {
  19892. return this.thicknessColorNode !== null;
  19893. }
  19894. /**
  19895. * Setups the lighting model.
  19896. *
  19897. * @return {SSSLightingModel} The lighting model.
  19898. */
  19899. setupLightingModel( /*builder*/ ) {
  19900. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  19901. }
  19902. }
  19903. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  19904. // dotNL will be from -1.0 to 1.0
  19905. const dotNL = normal.dot( lightDirection );
  19906. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  19907. if ( builder.material.gradientMap ) {
  19908. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  19909. return vec3( gradientMap.r );
  19910. } else {
  19911. const fw = coord.fwidth().mul( 0.5 );
  19912. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  19913. }
  19914. } );
  19915. /**
  19916. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  19917. *
  19918. * @augments LightingModel
  19919. */
  19920. class ToonLightingModel extends LightingModel {
  19921. /**
  19922. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  19923. * reduced to a small number of discrete shades to create a comic-like, flat look.
  19924. *
  19925. * @param {Object} lightData - The light data.
  19926. * @param {NodeBuilder} builder - The current node builder.
  19927. */
  19928. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  19929. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  19930. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  19931. }
  19932. /**
  19933. * Implements the indirect lighting.
  19934. *
  19935. * @param {NodeBuilder} builder - The current node builder.
  19936. */
  19937. indirect( builder ) {
  19938. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  19939. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  19940. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  19941. }
  19942. }
  19943. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  19944. /**
  19945. * Node material version of {@link MeshToonMaterial}.
  19946. *
  19947. * @augments NodeMaterial
  19948. */
  19949. class MeshToonNodeMaterial extends NodeMaterial {
  19950. static get type() {
  19951. return 'MeshToonNodeMaterial';
  19952. }
  19953. /**
  19954. * Constructs a new mesh toon node material.
  19955. *
  19956. * @param {Object} [parameters] - The configuration parameter.
  19957. */
  19958. constructor( parameters ) {
  19959. super();
  19960. /**
  19961. * This flag can be used for type testing.
  19962. *
  19963. * @type {boolean}
  19964. * @readonly
  19965. * @default true
  19966. */
  19967. this.isMeshToonNodeMaterial = true;
  19968. /**
  19969. * Set to `true` because toon materials react on lights.
  19970. *
  19971. * @type {boolean}
  19972. * @default true
  19973. */
  19974. this.lights = true;
  19975. this.setDefaultValues( _defaultValues$4 );
  19976. this.setValues( parameters );
  19977. }
  19978. /**
  19979. * Setups the lighting model.
  19980. *
  19981. * @return {ToonLightingModel} The lighting model.
  19982. */
  19983. setupLightingModel( /*builder*/ ) {
  19984. return new ToonLightingModel();
  19985. }
  19986. }
  19987. /**
  19988. * TSL function for creating a matcap uv node.
  19989. *
  19990. * Can be used to compute texture coordinates for projecting a
  19991. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  19992. *
  19993. * @tsl
  19994. * @function
  19995. * @returns {Node<vec2>} The matcap UV coordinates.
  19996. */
  19997. const matcapUV = /*@__PURE__*/ Fn( () => {
  19998. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  19999. const y = positionViewDirection.cross( x );
  20000. return vec2( x.dot( normalView ), y.dot( normalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  20001. } ).once( [ 'NORMAL', 'VERTEX' ] )().toVar( 'matcapUV' );
  20002. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  20003. /**
  20004. * Node material version of {@link MeshMatcapMaterial}.
  20005. *
  20006. * @augments NodeMaterial
  20007. */
  20008. class MeshMatcapNodeMaterial extends NodeMaterial {
  20009. static get type() {
  20010. return 'MeshMatcapNodeMaterial';
  20011. }
  20012. /**
  20013. * Constructs a new mesh normal node material.
  20014. *
  20015. * @param {Object} [parameters] - The configuration parameter.
  20016. */
  20017. constructor( parameters ) {
  20018. super();
  20019. /**
  20020. * This flag can be used for type testing.
  20021. *
  20022. * @type {boolean}
  20023. * @readonly
  20024. * @default true
  20025. */
  20026. this.isMeshMatcapNodeMaterial = true;
  20027. this.setDefaultValues( _defaultValues$3 );
  20028. this.setValues( parameters );
  20029. }
  20030. /**
  20031. * Setups the matcap specific node variables.
  20032. *
  20033. * @param {NodeBuilder} builder - The current node builder.
  20034. */
  20035. setupVariants( builder ) {
  20036. const uv = matcapUV;
  20037. let matcapColor;
  20038. if ( builder.material.matcap ) {
  20039. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  20040. } else {
  20041. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  20042. }
  20043. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  20044. }
  20045. }
  20046. /**
  20047. * Applies a rotation to the given position node.
  20048. *
  20049. * @augments TempNode
  20050. */
  20051. class RotateNode extends TempNode {
  20052. static get type() {
  20053. return 'RotateNode';
  20054. }
  20055. /**
  20056. * Constructs a new rotate node.
  20057. *
  20058. * @param {Node} positionNode - The position node.
  20059. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  20060. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  20061. */
  20062. constructor( positionNode, rotationNode ) {
  20063. super();
  20064. /**
  20065. * The position node.
  20066. *
  20067. * @type {Node}
  20068. */
  20069. this.positionNode = positionNode;
  20070. /**
  20071. * Represents the rotation that is applied to the position node.
  20072. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  20073. *
  20074. * @type {Node}
  20075. */
  20076. this.rotationNode = rotationNode;
  20077. }
  20078. /**
  20079. * The type of the {@link RotateNode#positionNode} defines the node's type.
  20080. *
  20081. * @param {NodeBuilder} builder - The current node builder.
  20082. * @return {string} The node's type.
  20083. */
  20084. generateNodeType( builder ) {
  20085. return this.positionNode.getNodeType( builder );
  20086. }
  20087. setup( builder ) {
  20088. const { rotationNode, positionNode } = this;
  20089. const nodeType = this.getNodeType( builder );
  20090. if ( nodeType === 'vec2' ) {
  20091. const cosAngle = rotationNode.cos();
  20092. const sinAngle = rotationNode.sin();
  20093. const rotationMatrix = mat2(
  20094. cosAngle, sinAngle,
  20095. sinAngle.negate(), cosAngle
  20096. );
  20097. return rotationMatrix.mul( positionNode );
  20098. } else {
  20099. const rotation = rotationNode;
  20100. 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 ) );
  20101. 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 ) );
  20102. 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 ) );
  20103. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  20104. }
  20105. }
  20106. }
  20107. /**
  20108. * TSL function for creating a rotate node.
  20109. *
  20110. * @tsl
  20111. * @function
  20112. * @param {Node} positionNode - The position node.
  20113. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  20114. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  20115. * @returns {RotateNode}
  20116. */
  20117. const rotate = /*@__PURE__*/ nodeProxy( RotateNode ).setParameterLength( 2 );
  20118. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  20119. /**
  20120. * Node material version of {@link SpriteMaterial}.
  20121. *
  20122. * @augments NodeMaterial
  20123. */
  20124. class SpriteNodeMaterial extends NodeMaterial {
  20125. static get type() {
  20126. return 'SpriteNodeMaterial';
  20127. }
  20128. /**
  20129. * Constructs a new sprite node material.
  20130. *
  20131. * @param {Object} [parameters] - The configuration parameter.
  20132. */
  20133. constructor( parameters ) {
  20134. super();
  20135. /**
  20136. * This flag can be used for type testing.
  20137. *
  20138. * @type {boolean}
  20139. * @readonly
  20140. * @default true
  20141. */
  20142. this.isSpriteNodeMaterial = true;
  20143. this._useSizeAttenuation = true;
  20144. /**
  20145. * This property makes it possible to define the position of the sprite with a
  20146. * node. That can be useful when the material is used with instanced rendering
  20147. * and node data are defined with an instanced attribute node:
  20148. * ```js
  20149. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  20150. * material.positionNode = instancedBufferAttribute( positionAttribute );
  20151. * ```
  20152. * Another possibility is to compute the instanced data with a compute shader:
  20153. * ```js
  20154. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  20155. * particleMaterial.positionNode = positionBuffer.toAttribute();
  20156. * ```
  20157. *
  20158. * @type {?Node<vec2>}
  20159. * @default null
  20160. */
  20161. this.positionNode = null;
  20162. /**
  20163. * The rotation of sprite materials is by default inferred from the `rotation`,
  20164. * property. This node property allows to overwrite the default and define
  20165. * the rotation with a node instead.
  20166. *
  20167. * If you don't want to overwrite the rotation but modify the existing
  20168. * value instead, use {@link materialRotation}.
  20169. *
  20170. * @type {?Node<float>}
  20171. * @default null
  20172. */
  20173. this.rotationNode = null;
  20174. /**
  20175. * This node property provides an additional way to scale sprites next to
  20176. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  20177. * is multiplied with the scale value of this node in the vertex shader.
  20178. *
  20179. * @type {?Node<vec2>}
  20180. * @default null
  20181. */
  20182. this.scaleNode = null;
  20183. /**
  20184. * In Sprites, the transparent property is enabled by default.
  20185. *
  20186. * @type {boolean}
  20187. * @default true
  20188. */
  20189. this.transparent = true;
  20190. this.setDefaultValues( _defaultValues$2 );
  20191. this.setValues( parameters );
  20192. }
  20193. /**
  20194. * Setups the position node in view space. This method implements
  20195. * the sprite specific vertex shader.
  20196. *
  20197. * @param {NodeBuilder} builder - The current node builder.
  20198. * @return {Node<vec3>} The position in view space.
  20199. */
  20200. setupPositionView( builder ) {
  20201. const { object, camera } = builder;
  20202. const { positionNode, rotationNode, scaleNode, sizeAttenuation } = this;
  20203. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  20204. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  20205. if ( scaleNode !== null ) {
  20206. scale = scale.mul( vec2( scaleNode ) );
  20207. }
  20208. if ( camera.isPerspectiveCamera && sizeAttenuation === false ) {
  20209. scale = scale.mul( mvPosition.z.negate() );
  20210. }
  20211. let alignedPosition = positionGeometry.xy;
  20212. if ( object.center && object.center.isVector2 === true ) {
  20213. const center = reference$1( 'center', 'vec2', object );
  20214. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  20215. }
  20216. alignedPosition = alignedPosition.mul( scale );
  20217. const rotation = float( rotationNode || materialRotation );
  20218. const rotatedPosition = rotate( alignedPosition, rotation );
  20219. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  20220. }
  20221. /**
  20222. * Whether to use size attenuation or not.
  20223. *
  20224. * @type {boolean}
  20225. * @default true
  20226. */
  20227. get sizeAttenuation() {
  20228. return this._useSizeAttenuation;
  20229. }
  20230. set sizeAttenuation( value ) {
  20231. if ( this._useSizeAttenuation !== value ) {
  20232. this._useSizeAttenuation = value;
  20233. this.needsUpdate = true;
  20234. }
  20235. }
  20236. }
  20237. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  20238. const _size$4 = /*@__PURE__*/ new Vector2();
  20239. /**
  20240. * Node material version of {@link PointsMaterial}.
  20241. *
  20242. * This material can be used in two ways:
  20243. *
  20244. * - By rendering point primitives with {@link Points}. Since WebGPU only supports point primitives
  20245. * with a pixel size of `1`, it's not possible to define a size.
  20246. *
  20247. * ```js
  20248. * const pointCloud = new THREE.Points( geometry, new THREE.PointsNodeMaterial() );
  20249. * ```
  20250. *
  20251. * - By rendering point primitives with {@link Sprites}. In this case, size is honored,
  20252. * see {@link PointsNodeMaterial#sizeNode}.
  20253. *
  20254. * ```js
  20255. * const instancedPoints = new THREE.Sprite( new THREE.PointsNodeMaterial( { positionNode: instancedBufferAttribute( positionAttribute ) } ) );
  20256. * ```
  20257. *
  20258. * @augments SpriteNodeMaterial
  20259. */
  20260. class PointsNodeMaterial extends SpriteNodeMaterial {
  20261. static get type() {
  20262. return 'PointsNodeMaterial';
  20263. }
  20264. /**
  20265. * Constructs a new points node material.
  20266. *
  20267. * @param {Object} [parameters] - The configuration parameter.
  20268. */
  20269. constructor( parameters ) {
  20270. super();
  20271. /**
  20272. * This node property provides an additional way to set the point size.
  20273. *
  20274. * Note that WebGPU only supports point primitives with 1 pixel size. Consequently,
  20275. * this node has no effect when the material is used with {@link Points} and a WebGPU
  20276. * backend. If an application wants to render points with a size larger than 1 pixel,
  20277. * the material should be used with {@link Sprite} and instancing.
  20278. *
  20279. * @type {?Node<vec2>}
  20280. * @default null
  20281. */
  20282. this.sizeNode = null;
  20283. /**
  20284. * This flag can be used for type testing.
  20285. *
  20286. * @type {boolean}
  20287. * @readonly
  20288. * @default true
  20289. */
  20290. this.isPointsNodeMaterial = true;
  20291. this.setDefaultValues( _defaultValues$1 );
  20292. this.setValues( parameters );
  20293. }
  20294. setupPositionView() {
  20295. const { positionNode } = this;
  20296. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  20297. }
  20298. setupVertexSprite( builder ) {
  20299. const { material, camera } = builder;
  20300. const { rotationNode, scaleNode, sizeNode, sizeAttenuation } = this;
  20301. let mvp = super.setupVertex( builder );
  20302. // skip further processing if the material is not a node material
  20303. if ( material.isNodeMaterial !== true ) {
  20304. return mvp;
  20305. }
  20306. // point size
  20307. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  20308. pointSize = pointSize.mul( screenDPR );
  20309. // size attenuation
  20310. if ( camera.isPerspectiveCamera && sizeAttenuation === true ) {
  20311. // follow WebGLRenderer's implementation, and scale by half the canvas height in logical units
  20312. pointSize = pointSize.mul( scale.div( positionView.z.negate() ) );
  20313. }
  20314. // scale
  20315. if ( scaleNode && scaleNode.isNode ) {
  20316. pointSize = pointSize.mul( vec2( scaleNode ) );
  20317. }
  20318. // compute offset
  20319. let offset = positionGeometry.xy;
  20320. // apply rotation
  20321. if ( rotationNode && rotationNode.isNode ) {
  20322. const rotation = float( rotationNode );
  20323. offset = rotate( offset, rotation );
  20324. }
  20325. // account for point size
  20326. offset = offset.mul( pointSize );
  20327. // scale by viewport size
  20328. offset = offset.div( viewportSize.div( 2 ) );
  20329. // compensate for the perspective divide
  20330. offset = offset.mul( mvp.w );
  20331. // add offset
  20332. mvp = mvp.add( vec4( offset, 0, 0 ) );
  20333. return mvp;
  20334. }
  20335. setupVertex( builder ) {
  20336. if ( builder.object.isPoints ) {
  20337. return super.setupVertex( builder );
  20338. } else {
  20339. return this.setupVertexSprite( builder );
  20340. }
  20341. }
  20342. /**
  20343. * Whether alpha to coverage should be used or not.
  20344. *
  20345. * @type {boolean}
  20346. * @default true
  20347. */
  20348. get alphaToCoverage() {
  20349. return this._useAlphaToCoverage;
  20350. }
  20351. set alphaToCoverage( value ) {
  20352. if ( this._useAlphaToCoverage !== value ) {
  20353. this._useAlphaToCoverage = value;
  20354. this.needsUpdate = true;
  20355. }
  20356. }
  20357. }
  20358. const scale = /*@__PURE__*/ uniform( 1 ).onFrameUpdate( function ( { renderer } ) {
  20359. const size = renderer.getSize( _size$4 ); // logical units
  20360. this.value = 0.5 * size.y;
  20361. } );
  20362. /**
  20363. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  20364. *
  20365. * @augments LightingModel
  20366. */
  20367. class ShadowMaskModel extends LightingModel {
  20368. /**
  20369. * Constructs a new shadow mask model.
  20370. */
  20371. constructor() {
  20372. super();
  20373. /**
  20374. * The shadow mask node.
  20375. *
  20376. * @type {Node}
  20377. */
  20378. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  20379. }
  20380. /**
  20381. * Only used to save the shadow mask.
  20382. *
  20383. * @param {Object} input - The input data.
  20384. */
  20385. direct( { lightNode } ) {
  20386. if ( lightNode.shadowNode !== null ) {
  20387. this.shadowNode.mulAssign( lightNode.shadowNode );
  20388. }
  20389. }
  20390. /**
  20391. * Uses the shadow mask to produce the final color.
  20392. *
  20393. * @param {NodeBuilder} builder - The current node builder.
  20394. */
  20395. finish( { context } ) {
  20396. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  20397. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  20398. }
  20399. }
  20400. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  20401. /**
  20402. * Node material version of {@link ShadowMaterial}.
  20403. *
  20404. * @augments NodeMaterial
  20405. */
  20406. class ShadowNodeMaterial extends NodeMaterial {
  20407. static get type() {
  20408. return 'ShadowNodeMaterial';
  20409. }
  20410. /**
  20411. * Constructs a new shadow node material.
  20412. *
  20413. * @param {Object} [parameters] - The configuration parameter.
  20414. */
  20415. constructor( parameters ) {
  20416. super();
  20417. /**
  20418. * This flag can be used for type testing.
  20419. *
  20420. * @type {boolean}
  20421. * @readonly
  20422. * @default true
  20423. */
  20424. this.isShadowNodeMaterial = true;
  20425. /**
  20426. * Set to `true` because so it's possible to implement
  20427. * the shadow mask effect.
  20428. *
  20429. * @type {boolean}
  20430. * @default true
  20431. */
  20432. this.lights = true;
  20433. /**
  20434. * Overwritten since shadow materials are transparent
  20435. * by default.
  20436. *
  20437. * @type {boolean}
  20438. * @default true
  20439. */
  20440. this.transparent = true;
  20441. this.setDefaultValues( _defaultValues );
  20442. this.setValues( parameters );
  20443. }
  20444. /**
  20445. * Setups the lighting model.
  20446. *
  20447. * @return {ShadowMaskModel} The lighting model.
  20448. */
  20449. setupLightingModel( /*builder*/ ) {
  20450. return new ShadowMaskModel();
  20451. }
  20452. }
  20453. const scatteringDensity = property( 'vec3' );
  20454. const linearDepthRay = property( 'vec3' );
  20455. const outgoingRayLight = property( 'vec3' );
  20456. /**
  20457. * VolumetricLightingModel class extends the LightingModel to implement volumetric lighting effects.
  20458. * This model calculates the scattering and transmittance of light through a volumetric medium.
  20459. * It dynamically adjusts the direction of the ray based on the camera and object positions.
  20460. * The model supports custom scattering and depth nodes to enhance the lighting effects.
  20461. *
  20462. * @augments LightingModel
  20463. */
  20464. class VolumetricLightingModel extends LightingModel {
  20465. constructor() {
  20466. super();
  20467. }
  20468. start( builder ) {
  20469. const { material } = builder;
  20470. const startPos = property( 'vec3' );
  20471. const endPos = property( 'vec3' );
  20472. // This approach dynamically changes the direction of the ray,
  20473. // prioritizing the ray from the camera to the object if it is inside the mesh, and from the object to the camera if it is far away.
  20474. const isFrontToBack = property( 'bool' );
  20475. If( cameraPosition.sub( positionWorld ).length().greaterThan( modelRadius.mul( 2 ) ), () => {
  20476. startPos.assign( cameraPosition );
  20477. endPos.assign( positionWorld );
  20478. isFrontToBack.assign( true );
  20479. } ).Else( () => {
  20480. startPos.assign( positionWorld );
  20481. endPos.assign( cameraPosition );
  20482. isFrontToBack.assign( false );
  20483. } );
  20484. //
  20485. const viewVector = endPos.sub( startPos );
  20486. const steps = uniform( 'int' ).onRenderUpdate( ( { material } ) => material.steps );
  20487. const stepSize = viewVector.length().div( steps ).toVar();
  20488. const rayDir = viewVector.normalize().toVar(); // TODO: toVar() should be automatic here ( in loop )
  20489. const distTravelled = float( 0.0 ).toVar();
  20490. const transmittance = vec3( 1 ).toVar();
  20491. if ( material.offsetNode ) {
  20492. // reduce banding
  20493. distTravelled.addAssign( material.offsetNode.mul( stepSize ) );
  20494. }
  20495. Loop( steps, () => {
  20496. const positionRay = startPos.add( rayDir.mul( distTravelled ) );
  20497. const positionViewRay = cameraViewMatrix.mul( vec4( positionRay, 1 ) ).xyz;
  20498. if ( material.depthNode !== null ) {
  20499. linearDepthRay.assign( linearDepth( viewZToPerspectiveDepth( positionViewRay.z, cameraNear, cameraFar ) ) );
  20500. builder.context.sceneDepthNode = linearDepth( material.depthNode ).toVar();
  20501. }
  20502. builder.context.positionWorld = positionRay;
  20503. builder.context.shadowPositionWorld = positionRay;
  20504. builder.context.positionView = positionViewRay;
  20505. scatteringDensity.assign( 0 );
  20506. let scatteringNode;
  20507. let scatteringEmissiveNode;
  20508. if ( material.scatteringNode ) {
  20509. scatteringNode = material.scatteringNode( { positionRay } );
  20510. }
  20511. if ( material.scatteringEmissiveNode ) {
  20512. scatteringEmissiveNode = material.scatteringEmissiveNode( { positionRay } );
  20513. }
  20514. super.start( builder );
  20515. if ( scatteringNode ) {
  20516. scatteringDensity.mulAssign( scatteringNode );
  20517. }
  20518. const stepLight = scatteringDensity.mul( 0.01 ).toVar();
  20519. if ( scatteringEmissiveNode ) {
  20520. stepLight.addAssign( scatteringEmissiveNode.mul( 0.01 ) );
  20521. }
  20522. // beer's law
  20523. const falloff = scatteringDensity.mul( .01 ).negate().mul( stepSize ).exp();
  20524. If( isFrontToBack, () => {
  20525. outgoingRayLight.addAssign( stepLight.mul( transmittance ).mul( stepSize ) );
  20526. } ).Else( () => {
  20527. outgoingRayLight.assign( outgoingRayLight.mul( falloff ).add( stepLight.mul( stepSize ) ) );
  20528. } );
  20529. transmittance.mulAssign( falloff );
  20530. // move along the ray
  20531. distTravelled.addAssign( stepSize );
  20532. } );
  20533. }
  20534. scatteringLight( lightColor, builder ) {
  20535. const sceneDepthNode = builder.context.sceneDepthNode;
  20536. if ( sceneDepthNode ) {
  20537. If( sceneDepthNode.greaterThanEqual( linearDepthRay ), () => {
  20538. scatteringDensity.addAssign( lightColor );
  20539. } );
  20540. } else {
  20541. scatteringDensity.addAssign( lightColor );
  20542. }
  20543. }
  20544. direct( { lightNode, lightColor }, builder ) {
  20545. // Ignore non-analytical lights and lights with infinite distance
  20546. if ( lightNode.isAnalyticLightNode !== true || lightNode.light.distance === undefined ) return;
  20547. // TODO: We need a viewportOpaque*() ( output, depth ) to fit with modern rendering approaches
  20548. const directLight = lightColor.xyz.toVar();
  20549. if ( lightNode.shadowNode !== null ) {
  20550. directLight.mulAssign( lightNode.shadowNode ); // it no should be necessary if used in the same render pass
  20551. }
  20552. this.scatteringLight( directLight, builder );
  20553. }
  20554. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight }, builder ) {
  20555. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  20556. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  20557. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  20558. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  20559. const P = builder.context.positionView;
  20560. const directLight = lightColor.xyz.mul( LTC_Evaluate_Volume( { P, p0, p1, p2, p3 } ) ).pow( 1.5 );
  20561. this.scatteringLight( directLight, builder );
  20562. }
  20563. finish( builder ) {
  20564. builder.context.outgoingLight.assign( outgoingRayLight );
  20565. }
  20566. }
  20567. /**
  20568. * Volume node material.
  20569. *
  20570. * @augments NodeMaterial
  20571. */
  20572. class VolumeNodeMaterial extends NodeMaterial {
  20573. static get type() {
  20574. return 'VolumeNodeMaterial';
  20575. }
  20576. /**
  20577. * Constructs a new volume node material.
  20578. *
  20579. * @param {Object} [parameters] - The configuration parameter.
  20580. */
  20581. constructor( parameters ) {
  20582. super();
  20583. /**
  20584. * This flag can be used for type testing.
  20585. *
  20586. * @type {boolean}
  20587. * @readonly
  20588. * @default true
  20589. */
  20590. this.isVolumeNodeMaterial = true;
  20591. /**
  20592. * Number of steps used for raymarching.
  20593. *
  20594. * @type {number}
  20595. * @default 25
  20596. */
  20597. this.steps = 25;
  20598. /**
  20599. * Offsets the distance a ray has been traveled through a volume.
  20600. * Can be used to implement dithering to reduce banding.
  20601. *
  20602. * @type {Node<float>}
  20603. * @default null
  20604. */
  20605. this.offsetNode = null;
  20606. /**
  20607. * Node used for scattering calculations.
  20608. *
  20609. * @type {Function|FunctionNode<vec4>}
  20610. * @default null
  20611. */
  20612. this.scatteringNode = null;
  20613. this.lights = true;
  20614. this.transparent = true;
  20615. this.side = BackSide;
  20616. this.depthTest = false;
  20617. this.depthWrite = false;
  20618. this.setValues( parameters );
  20619. }
  20620. setupLightingModel() {
  20621. return new VolumetricLightingModel();
  20622. }
  20623. }
  20624. /**
  20625. * This module manages the internal animation loop of the renderer.
  20626. *
  20627. * @private
  20628. */
  20629. class Animation {
  20630. /**
  20631. * Constructs a new animation loop management component.
  20632. *
  20633. * @param {Renderer} renderer - A reference to the main renderer.
  20634. * @param {NodeManager} nodes - Renderer component for managing nodes related logic.
  20635. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20636. */
  20637. constructor( renderer, nodes, info ) {
  20638. /**
  20639. * A reference to the main renderer.
  20640. *
  20641. * @type {Renderer}
  20642. */
  20643. this.renderer = renderer;
  20644. /**
  20645. * Renderer component for managing nodes related logic.
  20646. *
  20647. * @type {NodeManager}
  20648. */
  20649. this.nodes = nodes;
  20650. /**
  20651. * Renderer component for managing metrics and monitoring data.
  20652. *
  20653. * @type {Info}
  20654. */
  20655. this.info = info;
  20656. /**
  20657. * A reference to the context from `requestAnimationFrame()` can
  20658. * be called (usually `window`).
  20659. *
  20660. * @type {?(Window|XRSession)}
  20661. */
  20662. this._context = typeof self !== 'undefined' ? self : null;
  20663. /**
  20664. * The user-defined animation loop.
  20665. *
  20666. * @type {?Function}
  20667. * @default null
  20668. */
  20669. this._animationLoop = null;
  20670. /**
  20671. * The requestId which is returned from the `requestAnimationFrame()` call.
  20672. * Can be used to cancel the stop the animation loop.
  20673. *
  20674. * @type {?number}
  20675. * @default null
  20676. */
  20677. this._requestId = null;
  20678. }
  20679. /**
  20680. * Starts the internal animation loop.
  20681. */
  20682. start() {
  20683. const update = ( time, xrFrame ) => {
  20684. this._requestId = this._context.requestAnimationFrame( update );
  20685. if ( this.info.autoReset === true ) this.info.reset();
  20686. this.nodes.nodeFrame.update();
  20687. this.info.frame = this.nodes.nodeFrame.frameId;
  20688. this.renderer._inspector.begin();
  20689. if ( this._animationLoop !== null ) this._animationLoop( time, xrFrame );
  20690. this.renderer._inspector.finish();
  20691. };
  20692. update();
  20693. }
  20694. /**
  20695. * Stops the internal animation loop.
  20696. */
  20697. stop() {
  20698. if ( this._context !== null ) this._context.cancelAnimationFrame( this._requestId );
  20699. this._requestId = null;
  20700. }
  20701. /**
  20702. * Returns the user-level animation loop.
  20703. *
  20704. * @return {?Function} The animation loop.
  20705. */
  20706. getAnimationLoop() {
  20707. return this._animationLoop;
  20708. }
  20709. /**
  20710. * Defines the user-level animation loop.
  20711. *
  20712. * @param {?Function} callback - The animation loop.
  20713. */
  20714. setAnimationLoop( callback ) {
  20715. this._animationLoop = callback;
  20716. }
  20717. /**
  20718. * Returns the animation context.
  20719. *
  20720. * @return {Window|XRSession} The animation context.
  20721. */
  20722. getContext() {
  20723. return this._context;
  20724. }
  20725. /**
  20726. * Defines the context in which `requestAnimationFrame()` is executed.
  20727. *
  20728. * @param {Window|XRSession} context - The context to set.
  20729. */
  20730. setContext( context ) {
  20731. this._context = context;
  20732. }
  20733. /**
  20734. * Frees all internal resources and stops the animation loop.
  20735. */
  20736. dispose() {
  20737. this.stop();
  20738. }
  20739. }
  20740. /**
  20741. * Data structure for the renderer. It allows defining values
  20742. * with chained, hierarchical keys. Keys are meant to be
  20743. * objects since the module internally works with Weak Maps
  20744. * for performance reasons.
  20745. *
  20746. * @private
  20747. */
  20748. class ChainMap {
  20749. /**
  20750. * Constructs a new Chain Map.
  20751. */
  20752. constructor() {
  20753. /**
  20754. * A map of Weak Maps by their key length.
  20755. *
  20756. * @type {Object<number, WeakMap>}
  20757. */
  20758. this.weakMaps = {};
  20759. }
  20760. /**
  20761. * Returns the Weak Map for the given keys.
  20762. *
  20763. * @param {Array<Object>} keys - List of keys.
  20764. * @return {WeakMap} The weak map.
  20765. */
  20766. _getWeakMap( keys ) {
  20767. const length = keys.length;
  20768. let weakMap = this.weakMaps[ length ];
  20769. if ( weakMap === undefined ) {
  20770. weakMap = new WeakMap();
  20771. this.weakMaps[ length ] = weakMap;
  20772. }
  20773. return weakMap;
  20774. }
  20775. /**
  20776. * Returns the value for the given array of keys.
  20777. *
  20778. * @param {Array<Object>} keys - List of keys.
  20779. * @return {any} The value. Returns `undefined` if no value was found.
  20780. */
  20781. get( keys ) {
  20782. let map = this._getWeakMap( keys );
  20783. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20784. map = map.get( keys[ i ] );
  20785. if ( map === undefined ) return undefined;
  20786. }
  20787. return map.get( keys[ keys.length - 1 ] );
  20788. }
  20789. /**
  20790. * Sets the value for the given keys.
  20791. *
  20792. * @param {Array<Object>} keys - List of keys.
  20793. * @param {any} value - The value to set.
  20794. * @return {ChainMap} A reference to this Chain Map.
  20795. */
  20796. set( keys, value ) {
  20797. let map = this._getWeakMap( keys );
  20798. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20799. const key = keys[ i ];
  20800. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  20801. map = map.get( key );
  20802. }
  20803. map.set( keys[ keys.length - 1 ], value );
  20804. return this;
  20805. }
  20806. /**
  20807. * Deletes a value for the given keys.
  20808. *
  20809. * @param {Array<Object>} keys - The keys.
  20810. * @return {boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  20811. */
  20812. delete( keys ) {
  20813. let map = this._getWeakMap( keys );
  20814. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20815. map = map.get( keys[ i ] );
  20816. if ( map === undefined ) return false;
  20817. }
  20818. return map.delete( keys[ keys.length - 1 ] );
  20819. }
  20820. }
  20821. let _id$a = 0;
  20822. const _protoKeysCache = new WeakMap();
  20823. function getKeys( obj ) {
  20824. const keys = Object.keys( obj );
  20825. let protoKeys = _protoKeysCache.get( obj.constructor );
  20826. if ( protoKeys === undefined ) {
  20827. protoKeys = [];
  20828. let proto = Object.getPrototypeOf( obj );
  20829. while ( proto ) {
  20830. const descriptors = Object.getOwnPropertyDescriptors( proto );
  20831. for ( const key in descriptors ) {
  20832. const descriptor = descriptors[ key ];
  20833. if ( descriptor && typeof descriptor.get === 'function' ) {
  20834. protoKeys.push( key );
  20835. }
  20836. }
  20837. proto = Object.getPrototypeOf( proto );
  20838. }
  20839. _protoKeysCache.set( obj.constructor, protoKeys );
  20840. }
  20841. for ( let i = 0; i < protoKeys.length; i ++ ) keys.push( protoKeys[ i ] );
  20842. return keys;
  20843. }
  20844. /**
  20845. * A render object is the renderer's representation of single entity that gets drawn
  20846. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  20847. * scene since render objects also depend from the used material, the current render context
  20848. * and the current scene's lighting.
  20849. *
  20850. * In general, the basic process of the renderer is:
  20851. *
  20852. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  20853. * - Process the render lists by calling one or more render commands for each render item.
  20854. * - For each render command, request a render object and perform the draw.
  20855. *
  20856. * The module provides an interface to get data required for the draw command like the actual
  20857. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  20858. * creating render objects should only be done when necessary.
  20859. *
  20860. * @private
  20861. */
  20862. class RenderObject {
  20863. /**
  20864. * Constructs a new render object.
  20865. *
  20866. * @param {NodeManager} nodes - Renderer component for managing nodes related logic.
  20867. * @param {Geometries} geometries - Renderer component for managing geometries.
  20868. * @param {Renderer} renderer - The renderer.
  20869. * @param {Object3D} object - The 3D object.
  20870. * @param {Material} material - The 3D object's material.
  20871. * @param {Scene} scene - The scene the 3D object belongs to.
  20872. * @param {Camera} camera - The camera the object should be rendered with.
  20873. * @param {LightsNode} lightsNode - The lights node.
  20874. * @param {RenderContext} renderContext - The render context.
  20875. * @param {ClippingContext} clippingContext - The clipping context.
  20876. */
  20877. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  20878. this.id = _id$a ++;
  20879. /**
  20880. * Renderer component for managing nodes related logic.
  20881. *
  20882. * @type {NodeManager}
  20883. * @private
  20884. */
  20885. this._nodes = nodes;
  20886. /**
  20887. * Renderer component for managing geometries.
  20888. *
  20889. * @type {Geometries}
  20890. * @private
  20891. */
  20892. this._geometries = geometries;
  20893. /**
  20894. * The renderer.
  20895. *
  20896. * @type {Renderer}
  20897. */
  20898. this.renderer = renderer;
  20899. /**
  20900. * The 3D object.
  20901. *
  20902. * @type {Object3D}
  20903. */
  20904. this.object = object;
  20905. /**
  20906. * The 3D object's material.
  20907. *
  20908. * @type {Material}
  20909. */
  20910. this.material = material;
  20911. /**
  20912. * The scene the 3D object belongs to.
  20913. *
  20914. * @type {Scene}
  20915. */
  20916. this.scene = scene;
  20917. /**
  20918. * The camera the 3D object should be rendered with.
  20919. *
  20920. * @type {Camera}
  20921. */
  20922. this.camera = camera;
  20923. /**
  20924. * The lights node.
  20925. *
  20926. * @type {LightsNode}
  20927. */
  20928. this.lightsNode = lightsNode;
  20929. /**
  20930. * The render context.
  20931. *
  20932. * @type {RenderContext}
  20933. */
  20934. this.context = renderContext;
  20935. /**
  20936. * The 3D object's geometry.
  20937. *
  20938. * @type {BufferGeometry}
  20939. */
  20940. this.geometry = object.geometry;
  20941. /**
  20942. * The render object's version.
  20943. *
  20944. * @type {number}
  20945. */
  20946. this.version = material.version;
  20947. /**
  20948. * The draw range of the geometry.
  20949. *
  20950. * @type {?Object}
  20951. * @default null
  20952. */
  20953. this.drawRange = null;
  20954. /**
  20955. * An array holding the buffer attributes
  20956. * of the render object. This entails attribute
  20957. * definitions on geometry and node level.
  20958. *
  20959. * @type {?Array<BufferAttribute>}
  20960. * @default null
  20961. */
  20962. this.attributes = null;
  20963. /**
  20964. * An object holding the version of the
  20965. * attributes. The keys are the attribute names
  20966. * and the values are the attribute versions.
  20967. *
  20968. * @type {?Object<string, number>}
  20969. * @default null
  20970. */
  20971. this.attributesId = null;
  20972. /**
  20973. * A reference to a render pipeline the render
  20974. * object is processed with.
  20975. *
  20976. * @type {RenderPipeline}
  20977. * @default null
  20978. */
  20979. this.pipeline = null;
  20980. /**
  20981. * Only relevant for objects using
  20982. * multiple materials. This represents a group entry
  20983. * from the respective `BufferGeometry`.
  20984. *
  20985. * @type {?{start: number, count: number}}
  20986. * @default null
  20987. */
  20988. this.group = null;
  20989. /**
  20990. * An array holding the vertex buffers which can
  20991. * be buffer attributes but also interleaved buffers.
  20992. *
  20993. * @type {?Array<BufferAttribute|InterleavedBuffer>}
  20994. * @default null
  20995. */
  20996. this.vertexBuffers = null;
  20997. /**
  20998. * The parameters for the draw command.
  20999. *
  21000. * @type {?Object}
  21001. * @default null
  21002. */
  21003. this.drawParams = null;
  21004. /**
  21005. * If this render object is used inside a render bundle,
  21006. * this property points to the respective bundle group.
  21007. *
  21008. * @type {?BundleGroup}
  21009. * @default null
  21010. */
  21011. this.bundle = null;
  21012. /**
  21013. * The clipping context.
  21014. *
  21015. * @type {ClippingContext}
  21016. */
  21017. this.clippingContext = clippingContext;
  21018. /**
  21019. * The clipping context's cache key.
  21020. *
  21021. * @type {string}
  21022. */
  21023. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  21024. /**
  21025. * The initial node cache key.
  21026. *
  21027. * @type {number}
  21028. */
  21029. this.initialNodesCacheKey = this.getDynamicCacheKey();
  21030. /**
  21031. * The initial cache key.
  21032. *
  21033. * @type {number}
  21034. */
  21035. this.initialCacheKey = this.getCacheKey();
  21036. /**
  21037. * The node builder state.
  21038. *
  21039. * @type {?NodeBuilderState}
  21040. * @private
  21041. * @default null
  21042. */
  21043. this._nodeBuilderState = null;
  21044. /**
  21045. * An array of bindings.
  21046. *
  21047. * @type {?Array<BindGroup>}
  21048. * @private
  21049. * @default null
  21050. */
  21051. this._bindings = null;
  21052. /**
  21053. * Reference to the node material observer.
  21054. *
  21055. * @type {?NodeMaterialObserver}
  21056. * @private
  21057. * @default null
  21058. */
  21059. this._monitor = null;
  21060. /**
  21061. * The object's original material when this render object is drawn with an
  21062. * override material.
  21063. *
  21064. * @type {?Material}
  21065. * @private
  21066. * @default null
  21067. */
  21068. this._sourceMaterial = renderer._currentSourceMaterial;
  21069. /**
  21070. * An event listener which is defined by `RenderObjects`. It performs
  21071. * clean up tasks when `dispose()` on this render object.
  21072. *
  21073. * @method
  21074. */
  21075. this.onDispose = null;
  21076. /**
  21077. * This flag can be used for type testing.
  21078. *
  21079. * @type {boolean}
  21080. * @readonly
  21081. * @default true
  21082. */
  21083. this.isRenderObject = true;
  21084. /**
  21085. * An event listener which is executed when `dispose()` is called on
  21086. * the material of this render object.
  21087. *
  21088. * @method
  21089. */
  21090. this.onMaterialDispose = () => {
  21091. this.dispose();
  21092. };
  21093. /**
  21094. * An event listener which is executed when `dispose()` is called on
  21095. * the geometry of this render object.
  21096. *
  21097. * @method
  21098. */
  21099. this.onGeometryDispose = () => {
  21100. // clear geometry cache attributes
  21101. this.attributes = null;
  21102. this.attributesId = null;
  21103. };
  21104. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  21105. this.geometry.addEventListener( 'dispose', this.onGeometryDispose );
  21106. if ( this._sourceMaterial !== null ) {
  21107. this._sourceMaterial.addEventListener( 'dispose', this.onMaterialDispose );
  21108. }
  21109. }
  21110. /**
  21111. * Updates the clipping context.
  21112. *
  21113. * @param {ClippingContext} context - The clipping context to set.
  21114. */
  21115. updateClipping( context ) {
  21116. this.clippingContext = context;
  21117. }
  21118. /**
  21119. * Whether the clipping requires an update or not.
  21120. *
  21121. * @type {boolean}
  21122. * @readonly
  21123. */
  21124. get clippingNeedsUpdate() {
  21125. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  21126. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  21127. return true;
  21128. }
  21129. /**
  21130. * The number of clipping planes defined in context of hardware clipping.
  21131. *
  21132. * @type {number}
  21133. * @readonly
  21134. */
  21135. get hardwareClippingPlanes() {
  21136. return this.getNodeBuilderState().hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  21137. }
  21138. /**
  21139. * Returns the node builder state of this render object.
  21140. *
  21141. * @return {NodeBuilderState} The node builder state.
  21142. */
  21143. getNodeBuilderState() {
  21144. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  21145. }
  21146. /**
  21147. * Returns the node material observer of this render object.
  21148. *
  21149. * @return {NodeMaterialObserver} The node material observer.
  21150. */
  21151. getMonitor() {
  21152. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  21153. }
  21154. /**
  21155. * Returns an array of bind groups of this render object.
  21156. *
  21157. * @return {Array<BindGroup>} The bindings.
  21158. */
  21159. getBindings() {
  21160. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  21161. }
  21162. /**
  21163. * Returns a binding group by group name of this render object.
  21164. *
  21165. * @param {string} name - The name of the binding group.
  21166. * @return {?BindGroup} The bindings.
  21167. */
  21168. getBindingGroup( name ) {
  21169. for ( const bindingGroup of this.getBindings() ) {
  21170. if ( bindingGroup.name === name ) {
  21171. return bindingGroup;
  21172. }
  21173. }
  21174. }
  21175. /**
  21176. * Returns the index of the render object's geometry.
  21177. *
  21178. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  21179. */
  21180. getIndex() {
  21181. return this._geometries.getIndex( this );
  21182. }
  21183. /**
  21184. * Returns the indirect buffer attribute.
  21185. *
  21186. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  21187. */
  21188. getIndirect() {
  21189. return this._geometries.getIndirect( this );
  21190. }
  21191. /**
  21192. * Returns the byte offset into the indirect attribute buffer.
  21193. *
  21194. * @return {number|Array<number>} The byte offset into the indirect attribute buffer.
  21195. */
  21196. getIndirectOffset() {
  21197. return this._geometries.getIndirectOffset( this );
  21198. }
  21199. /**
  21200. * Returns an array that acts as a key for identifying the render object in a chain map.
  21201. *
  21202. * @return {Array<Object>} An array with object references.
  21203. */
  21204. getChainArray() {
  21205. return [ this.object, this.material, this.context, this.lightsNode ];
  21206. }
  21207. /**
  21208. * This method is used when the geometry of a 3D object has been exchanged and the
  21209. * respective render object now requires an update.
  21210. *
  21211. * @param {BufferGeometry} geometry - The geometry to set.
  21212. */
  21213. setGeometry( geometry ) {
  21214. this.geometry = geometry;
  21215. this.attributes = null;
  21216. this.attributesId = null;
  21217. }
  21218. /**
  21219. * Returns the buffer attributes of the render object. The returned array holds
  21220. * attribute definitions on geometry and node level.
  21221. *
  21222. * @return {Array<BufferAttribute>} An array with buffer attributes.
  21223. */
  21224. getAttributes() {
  21225. if ( this.attributes !== null ) return this.attributes;
  21226. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  21227. const geometry = this.geometry;
  21228. const attributes = [];
  21229. const vertexBuffers = new Set();
  21230. const attributesId = {};
  21231. for ( const nodeAttribute of nodeAttributes ) {
  21232. let attribute;
  21233. if ( nodeAttribute.node && nodeAttribute.node.attribute ) {
  21234. // node attribute
  21235. attribute = nodeAttribute.node.attribute;
  21236. } else {
  21237. // geometry attribute
  21238. attribute = geometry.getAttribute( nodeAttribute.name );
  21239. if ( attribute !== undefined ) {
  21240. if ( attribute.isInterleavedBufferAttribute ) {
  21241. attributesId[ nodeAttribute.name ] = attribute.data.uuid;
  21242. } else {
  21243. attributesId[ nodeAttribute.name ] = attribute.id;
  21244. }
  21245. }
  21246. }
  21247. if ( attribute === undefined ) continue;
  21248. attributes.push( attribute );
  21249. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  21250. vertexBuffers.add( bufferAttribute );
  21251. }
  21252. this.attributes = attributes;
  21253. this.attributesId = attributesId;
  21254. this.vertexBuffers = Array.from( vertexBuffers.values() );
  21255. return attributes;
  21256. }
  21257. /**
  21258. * Returns the vertex buffers of the render object.
  21259. *
  21260. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  21261. */
  21262. getVertexBuffers() {
  21263. if ( this.vertexBuffers === null ) this.getAttributes();
  21264. return this.vertexBuffers;
  21265. }
  21266. /**
  21267. * Returns the draw parameters for the render object.
  21268. *
  21269. * @return {?{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} The draw parameters.
  21270. */
  21271. getDrawParameters() {
  21272. const { object, material, geometry, group, drawRange } = this;
  21273. const drawParams = this.drawParams || ( this.drawParams = {
  21274. vertexCount: 0,
  21275. firstVertex: 0,
  21276. instanceCount: 0,
  21277. firstInstance: 0
  21278. } );
  21279. const index = this.getIndex();
  21280. const hasIndex = ( index !== null );
  21281. let instanceCount = 1;
  21282. if ( geometry.isInstancedBufferGeometry === true ) {
  21283. instanceCount = geometry.instanceCount;
  21284. } else if ( object.count !== undefined ) {
  21285. instanceCount = Math.max( 0, object.count );
  21286. }
  21287. if ( instanceCount === 0 ) return null;
  21288. drawParams.instanceCount = instanceCount;
  21289. if ( object.isBatchedMesh === true ) return drawParams;
  21290. let rangeFactor = 1;
  21291. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  21292. rangeFactor = 2;
  21293. }
  21294. let firstVertex = drawRange.start * rangeFactor;
  21295. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  21296. if ( group !== null ) {
  21297. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  21298. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  21299. }
  21300. const position = geometry.attributes.position;
  21301. let itemCount = Infinity;
  21302. if ( hasIndex ) {
  21303. itemCount = index.count;
  21304. } else if ( position !== undefined && position !== null ) {
  21305. itemCount = position.count;
  21306. }
  21307. firstVertex = Math.max( firstVertex, 0 );
  21308. lastVertex = Math.min( lastVertex, itemCount );
  21309. const count = lastVertex - firstVertex;
  21310. if ( count < 0 || count === Infinity ) return null;
  21311. drawParams.vertexCount = count;
  21312. drawParams.firstVertex = firstVertex;
  21313. return drawParams;
  21314. }
  21315. /**
  21316. * Returns the render object's geometry cache key.
  21317. *
  21318. * The geometry cache key is part of the material cache key.
  21319. *
  21320. * @return {string} The geometry cache key.
  21321. */
  21322. getGeometryCacheKey() {
  21323. const { geometry } = this;
  21324. let cacheKey = '';
  21325. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  21326. const attribute = geometry.attributes[ name ];
  21327. cacheKey += name + ',';
  21328. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  21329. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  21330. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  21331. if ( attribute.normalized ) cacheKey += 'n,';
  21332. }
  21333. // structural equality isn't sufficient for morph targets since the
  21334. // data are maintained in textures. only if the targets are all equal
  21335. // the texture and thus the `morphReference` can be shared.
  21336. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  21337. const targets = geometry.morphAttributes[ name ];
  21338. cacheKey += 'morph-' + name + ',';
  21339. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  21340. const attribute = targets[ i ];
  21341. cacheKey += attribute.id + ',';
  21342. }
  21343. }
  21344. if ( geometry.index ) {
  21345. cacheKey += 'index,';
  21346. }
  21347. return cacheKey;
  21348. }
  21349. /**
  21350. * Returns the render object's material cache key.
  21351. *
  21352. * The material cache key is part of the render object cache key.
  21353. *
  21354. * @return {number} The material cache key.
  21355. */
  21356. getMaterialCacheKey() {
  21357. const { object, material, renderer } = this;
  21358. let cacheKey = material.customProgramCacheKey();
  21359. for ( const property of getKeys( material ) ) {
  21360. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  21361. const value = material[ property ];
  21362. let valueKey;
  21363. if ( value !== null ) {
  21364. // some material values require a formatting
  21365. const type = typeof value;
  21366. if ( type === 'number' ) {
  21367. if ( property === 'side' ) {
  21368. // `side` is an enum (FrontSide/BackSide/DoubleSide) that changes code
  21369. // generation, so its exact value must be preserved.
  21370. valueKey = String( value );
  21371. } else {
  21372. // Other numbers are reduced to on/off
  21373. valueKey = value !== 0 ? '1' : '0';
  21374. }
  21375. } else if ( type === 'object' ) {
  21376. valueKey = '{';
  21377. if ( value.isTexture ) {
  21378. valueKey += value.mapping;
  21379. // WebGPU must honor the sampler data because they are part of the bindings
  21380. if ( renderer.backend.isWebGPUBackend === true ) {
  21381. valueKey += value.magFilter;
  21382. valueKey += value.minFilter;
  21383. valueKey += value.wrapS;
  21384. valueKey += value.wrapT;
  21385. valueKey += value.wrapR;
  21386. }
  21387. }
  21388. valueKey += '}';
  21389. } else {
  21390. valueKey = String( value );
  21391. }
  21392. } else {
  21393. valueKey = String( value );
  21394. }
  21395. cacheKey += /*property + ':' +*/ valueKey + ',';
  21396. }
  21397. cacheKey += this.clippingContextCacheKey + ',';
  21398. if ( object.geometry ) {
  21399. cacheKey += this.getGeometryCacheKey();
  21400. }
  21401. if ( object.skeleton ) {
  21402. cacheKey += object.skeleton.bones.length + ',';
  21403. }
  21404. if ( object.isBatchedMesh ) {
  21405. cacheKey += object._matricesTexture.uuid + ',';
  21406. if ( object._colorsTexture !== null ) {
  21407. cacheKey += object._colorsTexture.uuid + ',';
  21408. }
  21409. }
  21410. if ( object.isInstancedMesh || object.count > 1 ) {
  21411. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  21412. cacheKey += object.uuid + ',';
  21413. }
  21414. cacheKey += this.context.id + ',';
  21415. cacheKey += object.receiveShadow + ',';
  21416. return hashString( cacheKey );
  21417. }
  21418. /**
  21419. * Whether the geometry requires an update or not.
  21420. *
  21421. * @type {boolean}
  21422. * @readonly
  21423. */
  21424. get needsGeometryUpdate() {
  21425. if ( this.geometry.id !== this.object.geometry.id ) return true;
  21426. if ( this.attributes !== null ) {
  21427. const attributesId = this.attributesId;
  21428. for ( const name in attributesId ) {
  21429. const attribute = this.geometry.getAttribute( name );
  21430. if ( attribute === undefined ) return true;
  21431. const id = attribute.isInterleavedBufferAttribute ? attribute.data.uuid : attribute.id;
  21432. if ( attributesId[ name ] !== id ) {
  21433. return true;
  21434. }
  21435. }
  21436. }
  21437. return false;
  21438. }
  21439. /**
  21440. * Whether the render object requires an update or not.
  21441. *
  21442. * Note: There are two distinct places where render objects are checked for an update.
  21443. *
  21444. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  21445. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  21446. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  21447. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  21448. * a need for a refresh due to material, geometry or object related value changes.
  21449. *
  21450. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  21451. * that performs the 'needsUpdate' check.
  21452. *
  21453. * @type {boolean}
  21454. * @readonly
  21455. */
  21456. get needsUpdate() {
  21457. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  21458. }
  21459. /**
  21460. * Returns the dynamic cache key which represents a key that is computed per draw command.
  21461. *
  21462. * @return {number} The cache key.
  21463. */
  21464. getDynamicCacheKey() {
  21465. let cacheKey = 0;
  21466. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  21467. // the renderer is inside a shadow pass.
  21468. if ( this.material.isShadowPassMaterial !== true ) {
  21469. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  21470. }
  21471. if ( this.camera.isArrayCamera ) {
  21472. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  21473. }
  21474. if ( this.object.receiveShadow ) {
  21475. cacheKey = hash$1( cacheKey, 1 );
  21476. }
  21477. cacheKey = hash$1( cacheKey, this.renderer.contextNode.id, this.renderer.contextNode.version );
  21478. return cacheKey;
  21479. }
  21480. /**
  21481. * Returns the render object's cache key.
  21482. *
  21483. * @return {number} The cache key.
  21484. */
  21485. getCacheKey() {
  21486. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  21487. }
  21488. /**
  21489. * Frees internal resources.
  21490. */
  21491. dispose() {
  21492. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  21493. this.geometry.removeEventListener( 'dispose', this.onGeometryDispose );
  21494. if ( this._sourceMaterial !== null ) {
  21495. this._sourceMaterial.removeEventListener( 'dispose', this.onMaterialDispose );
  21496. }
  21497. this.onDispose();
  21498. }
  21499. }
  21500. const _chainKeys$3 = [];
  21501. /**
  21502. * This module manages the render objects of the renderer.
  21503. *
  21504. * @private
  21505. */
  21506. class RenderObjects {
  21507. /**
  21508. * Constructs a new render object management component.
  21509. *
  21510. * @param {Renderer} renderer - The renderer.
  21511. * @param {NodeManager} nodes - Renderer component for managing nodes related logic.
  21512. * @param {Geometries} geometries - Renderer component for managing geometries.
  21513. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  21514. * @param {Bindings} bindings - Renderer component for managing bindings.
  21515. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21516. */
  21517. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  21518. /**
  21519. * The renderer.
  21520. *
  21521. * @type {Renderer}
  21522. */
  21523. this.renderer = renderer;
  21524. /**
  21525. * Renderer component for managing nodes related logic.
  21526. *
  21527. * @type {NodeManager}
  21528. */
  21529. this.nodes = nodes;
  21530. /**
  21531. * Renderer component for managing geometries.
  21532. *
  21533. * @type {Geometries}
  21534. */
  21535. this.geometries = geometries;
  21536. /**
  21537. * Renderer component for managing pipelines.
  21538. *
  21539. * @type {Pipelines}
  21540. */
  21541. this.pipelines = pipelines;
  21542. /**
  21543. * Renderer component for managing bindings.
  21544. *
  21545. * @type {Bindings}
  21546. */
  21547. this.bindings = bindings;
  21548. /**
  21549. * Renderer component for managing metrics and monitoring data.
  21550. *
  21551. * @type {Info}
  21552. */
  21553. this.info = info;
  21554. /**
  21555. * A dictionary that manages render contexts in chain maps
  21556. * for each pass ID.
  21557. *
  21558. * @type {Object<string,ChainMap>}
  21559. */
  21560. this.chainMaps = {};
  21561. }
  21562. /**
  21563. * Returns a render object for the given object and state data.
  21564. *
  21565. * @param {Object3D} object - The 3D object.
  21566. * @param {Material} material - The 3D object's material.
  21567. * @param {Scene} scene - The scene the 3D object belongs to.
  21568. * @param {Camera} camera - The camera the 3D object should be rendered with.
  21569. * @param {LightsNode} lightsNode - The lights node.
  21570. * @param {RenderContext} renderContext - The render context.
  21571. * @param {ClippingContext} clippingContext - The clipping context.
  21572. * @param {string} [passId] - An optional ID for identifying the pass.
  21573. * @return {RenderObject} The render object.
  21574. */
  21575. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  21576. const chainMap = this.getChainMap( passId );
  21577. // set chain keys
  21578. _chainKeys$3[ 0 ] = object;
  21579. _chainKeys$3[ 1 ] = material;
  21580. _chainKeys$3[ 2 ] = renderContext;
  21581. _chainKeys$3[ 3 ] = lightsNode;
  21582. //
  21583. let renderObject = chainMap.get( _chainKeys$3 );
  21584. if ( renderObject === undefined ) {
  21585. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  21586. chainMap.set( _chainKeys$3, renderObject );
  21587. } else {
  21588. // update references
  21589. renderObject.camera = camera;
  21590. //
  21591. renderObject.updateClipping( clippingContext );
  21592. if ( renderObject.needsGeometryUpdate ) {
  21593. renderObject.setGeometry( object.geometry );
  21594. }
  21595. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  21596. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  21597. renderObject.dispose();
  21598. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  21599. } else {
  21600. renderObject.version = material.version;
  21601. }
  21602. }
  21603. }
  21604. // reset chain array
  21605. _chainKeys$3[ 0 ] = null;
  21606. _chainKeys$3[ 1 ] = null;
  21607. _chainKeys$3[ 2 ] = null;
  21608. _chainKeys$3[ 3 ] = null;
  21609. //
  21610. return renderObject;
  21611. }
  21612. /**
  21613. * Returns a chain map for the given pass ID.
  21614. *
  21615. * @param {string} [passId='default'] - The pass ID.
  21616. * @return {ChainMap} The chain map.
  21617. */
  21618. getChainMap( passId = 'default' ) {
  21619. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  21620. }
  21621. /**
  21622. * Frees internal resources.
  21623. */
  21624. dispose() {
  21625. this.chainMaps = {};
  21626. }
  21627. /**
  21628. * Factory method for creating render objects with the given list of parameters.
  21629. *
  21630. * @param {NodeManager} nodes - Renderer component for managing nodes related logic.
  21631. * @param {Geometries} geometries - Renderer component for managing geometries.
  21632. * @param {Renderer} renderer - The renderer.
  21633. * @param {Object3D} object - The 3D object.
  21634. * @param {Material} material - The object's material.
  21635. * @param {Scene} scene - The scene the 3D object belongs to.
  21636. * @param {Camera} camera - The camera the object should be rendered with.
  21637. * @param {LightsNode} lightsNode - The lights node.
  21638. * @param {RenderContext} renderContext - The render context.
  21639. * @param {ClippingContext} clippingContext - The clipping context.
  21640. * @param {string} [passId] - An optional ID for identifying the pass.
  21641. * @return {RenderObject} The render object.
  21642. */
  21643. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  21644. const chainMap = this.getChainMap( passId );
  21645. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  21646. renderObject.onDispose = () => {
  21647. this.pipelines.delete( renderObject );
  21648. this.bindings.deleteForRender( renderObject );
  21649. this.nodes.delete( renderObject );
  21650. chainMap.delete( renderObject.getChainArray() );
  21651. };
  21652. return renderObject;
  21653. }
  21654. }
  21655. /**
  21656. * Data structure for the renderer. It is intended to manage
  21657. * data of objects in dictionaries.
  21658. *
  21659. * @private
  21660. */
  21661. class DataMap {
  21662. /**
  21663. * Constructs a new data map.
  21664. */
  21665. constructor() {
  21666. /**
  21667. * `DataMap` internally uses a weak map
  21668. * to manage its data.
  21669. *
  21670. * @type {WeakMap<Object, Object>}
  21671. */
  21672. this.data = new WeakMap();
  21673. }
  21674. /**
  21675. * Returns the dictionary for the given object.
  21676. *
  21677. * @param {Object} object - The object.
  21678. * @return {Object} The dictionary.
  21679. */
  21680. get( object ) {
  21681. let map = this.data.get( object );
  21682. if ( map === undefined ) {
  21683. map = {};
  21684. this.data.set( object, map );
  21685. }
  21686. return map;
  21687. }
  21688. /**
  21689. * Deletes the dictionary for the given object.
  21690. *
  21691. * @param {Object} object - The object.
  21692. * @return {?Object} The deleted dictionary.
  21693. */
  21694. delete( object ) {
  21695. let map = null;
  21696. if ( this.data.has( object ) ) {
  21697. map = this.data.get( object );
  21698. this.data.delete( object );
  21699. }
  21700. return map;
  21701. }
  21702. /**
  21703. * Returns `true` if the given object has a dictionary defined.
  21704. *
  21705. * @param {Object} object - The object to test.
  21706. * @return {boolean} Whether a dictionary is defined or not.
  21707. */
  21708. has( object ) {
  21709. return this.data.has( object );
  21710. }
  21711. /**
  21712. * Frees internal resources.
  21713. */
  21714. dispose() {
  21715. this.data = new WeakMap();
  21716. }
  21717. }
  21718. const AttributeType = {
  21719. VERTEX: 1,
  21720. INDEX: 2,
  21721. STORAGE: 3,
  21722. INDIRECT: 4
  21723. };
  21724. // size of a chunk in bytes (STD140 layout)
  21725. const GPU_CHUNK_BYTES = 16;
  21726. // @TODO: Move to src/constants.js
  21727. const BlendColorFactor = 211;
  21728. const OneMinusBlendColorFactor = 212;
  21729. /**
  21730. * This renderer module manages geometry attributes.
  21731. *
  21732. * @private
  21733. * @augments DataMap
  21734. */
  21735. class Attributes extends DataMap {
  21736. /**
  21737. * Constructs a new attribute management component.
  21738. *
  21739. * @param {Backend} backend - The renderer's backend.
  21740. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21741. */
  21742. constructor( backend, info ) {
  21743. super();
  21744. /**
  21745. * The renderer's backend.
  21746. *
  21747. * @type {Backend}
  21748. */
  21749. this.backend = backend;
  21750. /**
  21751. * Renderer component for managing metrics and monitoring data.
  21752. *
  21753. * @type {Info}
  21754. */
  21755. this.info = info;
  21756. }
  21757. /**
  21758. * Deletes the data for the given attribute.
  21759. *
  21760. * @param {BufferAttribute} attribute - The attribute.
  21761. * @return {?Object} The deleted attribute data.
  21762. */
  21763. delete( attribute ) {
  21764. const attributeData = super.delete( attribute );
  21765. if ( attributeData !== null ) {
  21766. this.backend.destroyAttribute( attribute );
  21767. this.info.destroyAttribute( attribute );
  21768. }
  21769. return attributeData;
  21770. }
  21771. /**
  21772. * Updates the given attribute. This method creates attribute buffers
  21773. * for new attributes and updates data for existing ones.
  21774. *
  21775. * @param {BufferAttribute} attribute - The attribute to update.
  21776. * @param {number} type - The attribute type.
  21777. */
  21778. update( attribute, type ) {
  21779. const data = this.get( attribute );
  21780. if ( data.version === undefined ) {
  21781. if ( type === AttributeType.VERTEX ) {
  21782. this.backend.createAttribute( attribute );
  21783. this.info.createAttribute( attribute );
  21784. } else if ( type === AttributeType.INDEX ) {
  21785. this.backend.createIndexAttribute( attribute );
  21786. this.info.createIndexAttribute( attribute );
  21787. } else if ( type === AttributeType.STORAGE ) {
  21788. this.backend.createStorageAttribute( attribute );
  21789. this.info.createStorageAttribute( attribute );
  21790. } else if ( type === AttributeType.INDIRECT ) {
  21791. this.backend.createIndirectStorageAttribute( attribute );
  21792. this.info.createIndirectStorageAttribute( attribute );
  21793. }
  21794. data.version = this._getBufferAttribute( attribute ).version;
  21795. } else {
  21796. const bufferAttribute = this._getBufferAttribute( attribute );
  21797. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  21798. this.backend.updateAttribute( attribute );
  21799. data.version = bufferAttribute.version;
  21800. }
  21801. }
  21802. }
  21803. /**
  21804. * Utility method for handling interleaved buffer attributes correctly.
  21805. * To process them, their `InterleavedBuffer` is returned.
  21806. *
  21807. * @param {BufferAttribute} attribute - The attribute.
  21808. * @return {BufferAttribute|InterleavedBuffer}
  21809. */
  21810. _getBufferAttribute( attribute ) {
  21811. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  21812. return attribute;
  21813. }
  21814. }
  21815. /**
  21816. * Returns the wireframe version for the given geometry.
  21817. *
  21818. * @private
  21819. * @function
  21820. * @param {BufferGeometry} geometry - The geometry.
  21821. * @return {number} The version.
  21822. */
  21823. function getWireframeVersion( geometry ) {
  21824. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  21825. }
  21826. /**
  21827. * Returns the wireframe ID for the given geometry.
  21828. *
  21829. * @private
  21830. * @function
  21831. * @param {BufferGeometry} geometry - The geometry.
  21832. * @return {number} The ID.
  21833. */
  21834. function getWireframeId( geometry ) {
  21835. return ( geometry.index !== null ) ? geometry.index.id : geometry.attributes.position.id;
  21836. }
  21837. /**
  21838. * Returns a wireframe index attribute for the given geometry.
  21839. *
  21840. * @private
  21841. * @function
  21842. * @param {BufferGeometry} geometry - The geometry.
  21843. * @return {BufferAttribute} The wireframe index attribute.
  21844. */
  21845. function getWireframeIndex( geometry ) {
  21846. const indices = [];
  21847. const geometryIndex = geometry.index;
  21848. const geometryPosition = geometry.attributes.position;
  21849. if ( geometryIndex !== null ) {
  21850. const array = geometryIndex.array;
  21851. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  21852. const a = array[ i + 0 ];
  21853. const b = array[ i + 1 ];
  21854. const c = array[ i + 2 ];
  21855. indices.push( a, b, b, c, c, a );
  21856. }
  21857. } else {
  21858. const array = geometryPosition.array;
  21859. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  21860. const a = i + 0;
  21861. const b = i + 1;
  21862. const c = i + 2;
  21863. indices.push( a, b, b, c, c, a );
  21864. }
  21865. }
  21866. const attribute = new ( geometryPosition.count >= 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  21867. attribute.version = getWireframeVersion( geometry );
  21868. attribute.__id = getWireframeId( geometry );
  21869. return attribute;
  21870. }
  21871. /**
  21872. * This renderer module manages geometries.
  21873. *
  21874. * @private
  21875. * @augments DataMap
  21876. */
  21877. class Geometries extends DataMap {
  21878. /**
  21879. * Constructs a new geometry management component.
  21880. *
  21881. * @param {Attributes} attributes - Renderer component for managing attributes.
  21882. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21883. */
  21884. constructor( attributes, info ) {
  21885. super();
  21886. /**
  21887. * Renderer component for managing attributes.
  21888. *
  21889. * @type {Attributes}
  21890. */
  21891. this.attributes = attributes;
  21892. /**
  21893. * Renderer component for managing metrics and monitoring data.
  21894. *
  21895. * @type {Info}
  21896. */
  21897. this.info = info;
  21898. /**
  21899. * Weak Map for managing attributes for wireframe rendering.
  21900. *
  21901. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  21902. */
  21903. this.wireframes = new WeakMap();
  21904. /**
  21905. * This Weak Map is used to make sure buffer attributes are
  21906. * updated only once per render call.
  21907. *
  21908. * @type {WeakMap<BufferAttribute,number>}
  21909. */
  21910. this.attributeCall = new WeakMap();
  21911. /**
  21912. * Stores the event listeners attached to geometries.
  21913. *
  21914. * @private
  21915. * @type {Map<BufferGeometry,Function>}
  21916. */
  21917. this._geometryDisposeListeners = new Map();
  21918. }
  21919. /**
  21920. * Returns `true` if the given render object has an initialized geometry.
  21921. *
  21922. * @param {RenderObject} renderObject - The render object.
  21923. * @return {boolean} Whether if the given render object has an initialized geometry or not.
  21924. */
  21925. has( renderObject ) {
  21926. const geometry = renderObject.geometry;
  21927. return super.has( geometry ) && this.get( geometry ).initialized === true;
  21928. }
  21929. /**
  21930. * Prepares the geometry of the given render object for rendering.
  21931. *
  21932. * @param {RenderObject} renderObject - The render object.
  21933. */
  21934. updateForRender( renderObject ) {
  21935. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  21936. this.updateAttributes( renderObject );
  21937. }
  21938. /**
  21939. * Initializes the geometry of the given render object.
  21940. *
  21941. * @param {RenderObject} renderObject - The render object.
  21942. */
  21943. initGeometry( renderObject ) {
  21944. const geometry = renderObject.geometry;
  21945. const geometryData = this.get( geometry );
  21946. geometryData.initialized = true;
  21947. this.info.memory.geometries ++;
  21948. const onDispose = () => {
  21949. this.info.memory.geometries --;
  21950. // index
  21951. const index = geometry.index;
  21952. if ( index !== null ) {
  21953. this.attributes.delete( index );
  21954. }
  21955. // geometry attributes
  21956. for ( const attribute of Object.values( geometry.attributes ) ) {
  21957. this.attributes.delete( attribute );
  21958. }
  21959. // wireframe attributes
  21960. const wireframeAttribute = this.wireframes.get( geometry );
  21961. if ( wireframeAttribute !== undefined ) {
  21962. this.attributes.delete( wireframeAttribute );
  21963. }
  21964. // node attributes (TODO: Remove this bit once we support BufferAttribute.dispose())
  21965. const currentAttributes = new Set( Object.values( renderObject.geometry.attributes ) );
  21966. for ( const attribute of renderObject.getAttributes() ) {
  21967. if ( currentAttributes.has( attribute ) === false ) {
  21968. this.attributes.delete( attribute );
  21969. }
  21970. }
  21971. //
  21972. geometry.removeEventListener( 'dispose', onDispose );
  21973. this._geometryDisposeListeners.delete( geometry );
  21974. };
  21975. geometry.addEventListener( 'dispose', onDispose );
  21976. // see #31798 why tracking separate remove listeners is required right now
  21977. // TODO: Re-evaluate how onDispose() is managed in this component
  21978. this._geometryDisposeListeners.set( geometry, onDispose );
  21979. }
  21980. /**
  21981. * Updates the geometry attributes of the given render object.
  21982. *
  21983. * @param {RenderObject} renderObject - The render object.
  21984. */
  21985. updateAttributes( renderObject ) {
  21986. // attributes
  21987. const attributes = renderObject.getAttributes();
  21988. for ( const attribute of attributes ) {
  21989. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  21990. this.updateAttribute( attribute, AttributeType.STORAGE );
  21991. } else {
  21992. this.updateAttribute( attribute, AttributeType.VERTEX );
  21993. }
  21994. }
  21995. // indexes
  21996. const index = this.getIndex( renderObject );
  21997. if ( index !== null ) {
  21998. this.updateAttribute( index, AttributeType.INDEX );
  21999. }
  22000. // indirect
  22001. const indirect = renderObject.geometry.indirect;
  22002. if ( indirect !== null ) {
  22003. this.updateAttribute( indirect, AttributeType.INDIRECT );
  22004. }
  22005. }
  22006. /**
  22007. * Updates the given attribute.
  22008. *
  22009. * @param {BufferAttribute} attribute - The attribute to update.
  22010. * @param {number} type - The attribute type.
  22011. */
  22012. updateAttribute( attribute, type ) {
  22013. const callId = this.info.render.calls;
  22014. if ( ! attribute.isInterleavedBufferAttribute ) {
  22015. if ( this.attributeCall.get( attribute ) !== callId ) {
  22016. this.attributes.update( attribute, type );
  22017. this.attributeCall.set( attribute, callId );
  22018. }
  22019. } else {
  22020. if ( this.attributeCall.get( attribute ) === undefined ) {
  22021. this.attributes.update( attribute, type );
  22022. this.attributeCall.set( attribute, callId );
  22023. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  22024. this.attributes.update( attribute, type );
  22025. this.attributeCall.set( attribute.data, callId );
  22026. this.attributeCall.set( attribute, callId );
  22027. }
  22028. }
  22029. }
  22030. /**
  22031. * Returns the indirect buffer attribute of the given render object.
  22032. *
  22033. * @param {RenderObject} renderObject - The render object.
  22034. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  22035. */
  22036. getIndirect( renderObject ) {
  22037. return renderObject.geometry.indirect;
  22038. }
  22039. /**
  22040. * Returns the byte offset into the indirect attribute buffer of the given render object.
  22041. *
  22042. * @param {RenderObject} renderObject - The render object.
  22043. * @return {number} The byte offset into the indirect attribute buffer.
  22044. */
  22045. getIndirectOffset( renderObject ) {
  22046. return renderObject.geometry.indirectOffset;
  22047. }
  22048. /**
  22049. * Returns the index of the given render object's geometry. This is implemented
  22050. * in a method to return a wireframe index if necessary.
  22051. *
  22052. * @param {RenderObject} renderObject - The render object.
  22053. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  22054. */
  22055. getIndex( renderObject ) {
  22056. const { geometry, material } = renderObject;
  22057. let index = geometry.index;
  22058. if ( material.wireframe === true ) {
  22059. const wireframes = this.wireframes;
  22060. let wireframeAttribute = wireframes.get( geometry );
  22061. if ( wireframeAttribute === undefined ) {
  22062. wireframeAttribute = getWireframeIndex( geometry );
  22063. wireframes.set( geometry, wireframeAttribute );
  22064. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) || wireframeAttribute.__id !== getWireframeId( geometry ) ) {
  22065. this.attributes.delete( wireframeAttribute );
  22066. wireframeAttribute = getWireframeIndex( geometry );
  22067. wireframes.set( geometry, wireframeAttribute );
  22068. }
  22069. index = wireframeAttribute;
  22070. }
  22071. return index;
  22072. }
  22073. dispose() {
  22074. for ( const [ geometry, onDispose ] of this._geometryDisposeListeners.entries() ) {
  22075. geometry.removeEventListener( 'dispose', onDispose );
  22076. }
  22077. this._geometryDisposeListeners.clear();
  22078. }
  22079. }
  22080. /**
  22081. * This renderer module provides a series of statistical information
  22082. * about the GPU memory and the rendering process. Useful for debugging
  22083. * and monitoring.
  22084. */
  22085. class Info {
  22086. /**
  22087. * Constructs a new info component.
  22088. */
  22089. constructor() {
  22090. /**
  22091. * Whether frame related metrics should automatically
  22092. * be resetted or not. This property should be set to `false`
  22093. * by apps which manage their own animation loop. They must
  22094. * then call `renderer.info.reset()` once per frame manually.
  22095. *
  22096. * @type {boolean}
  22097. * @default true
  22098. */
  22099. this.autoReset = true;
  22100. /**
  22101. * The current frame ID. This ID is managed
  22102. * by `NodeFrame`.
  22103. *
  22104. * @type {number}
  22105. * @readonly
  22106. * @default 0
  22107. */
  22108. this.frame = 0;
  22109. /**
  22110. * The number of render calls since the
  22111. * app has been started.
  22112. *
  22113. * @type {number}
  22114. * @readonly
  22115. * @default 0
  22116. */
  22117. this.calls = 0;
  22118. /**
  22119. * Render related metrics.
  22120. *
  22121. * @type {Object}
  22122. * @readonly
  22123. * @property {number} calls - The number of render calls since the app has been started.
  22124. * @property {number} frameCalls - The number of render calls of the current frame.
  22125. * @property {number} drawCalls - The number of draw calls of the current frame.
  22126. * @property {number} triangles - The number of rendered triangle primitives of the current frame.
  22127. * @property {number} points - The number of rendered point primitives of the current frame.
  22128. * @property {number} lines - The number of rendered line primitives of the current frame.
  22129. * @property {number} timestamp - The timestamp of the frame.
  22130. */
  22131. this.render = {
  22132. calls: 0,
  22133. frameCalls: 0,
  22134. drawCalls: 0,
  22135. triangles: 0,
  22136. points: 0,
  22137. lines: 0,
  22138. timestamp: 0,
  22139. };
  22140. /**
  22141. * Compute related metrics.
  22142. *
  22143. * @type {Object}
  22144. * @readonly
  22145. * @property {number} calls - The number of compute calls since the app has been started.
  22146. * @property {number} frameCalls - The number of compute calls of the current frame.
  22147. * @property {number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  22148. */
  22149. this.compute = {
  22150. calls: 0,
  22151. frameCalls: 0,
  22152. timestamp: 0
  22153. };
  22154. /**
  22155. * Memory related metrics.
  22156. *
  22157. * @type {Object}
  22158. * @readonly
  22159. * @property {number} attributes - The number of active attributes.
  22160. * @property {number} attributesSize - The memory size of active attributes in bytes.
  22161. * @property {number} geometries - The number of active geometries.
  22162. * @property {number} indexAttributes - The number of active index attributes.
  22163. * @property {number} indexAttributesSize - The memory size of active index attributes in bytes.
  22164. * @property {number} indirectStorageAttributes - The number of active indirect storage attributes.
  22165. * @property {number} indirectStorageAttributesSize - The memory size of active indirect storage attributes in bytes.
  22166. * @property {number} programs - The number of active programs.
  22167. * @property {number} programsSize - The memory size of active programs in bytes.
  22168. * @property {number} readbackBuffers - The number of active readback buffers.
  22169. * @property {number} readbackBuffersSize - The memory size of active readback buffers in bytes.
  22170. * @property {number} renderTargets - The number of active renderTargets.
  22171. * @property {number} storageAttributes - The number of active storage attributes.
  22172. * @property {number} storageAttributesSize - The memory size of active storage attributes in bytes.
  22173. * @property {number} textures - The number of active textures.
  22174. * @property {number} texturesSize - The memory size of active textures in bytes.
  22175. * @property {number} uniformBuffers - The number of active uniform buffers.
  22176. * @property {number} uniformBuffersSize - The memory size of active uniform buffers in bytes.
  22177. * @property {number} total - The total memory size in bytes.
  22178. */
  22179. this.memory = {
  22180. attributes: 0,
  22181. attributesSize: 0,
  22182. geometries: 0,
  22183. indexAttributes: 0,
  22184. indexAttributesSize: 0,
  22185. indirectStorageAttributes: 0,
  22186. indirectStorageAttributesSize: 0,
  22187. programs: 0,
  22188. programsSize: 0,
  22189. readbackBuffers: 0,
  22190. readbackBuffersSize: 0,
  22191. renderTargets: 0,
  22192. storageAttributes: 0,
  22193. storageAttributesSize: 0,
  22194. textures: 0,
  22195. texturesSize: 0,
  22196. uniformBuffers: 0,
  22197. uniformBuffersSize: 0,
  22198. total: 0
  22199. };
  22200. /**
  22201. * Map for storing calculated byte sizes of tracked objects.
  22202. *
  22203. * @type {Map<Object, number>}
  22204. * @private
  22205. */
  22206. this.memoryMap = new Map();
  22207. }
  22208. /**
  22209. * This method should be executed per draw call and updates the corresponding metrics.
  22210. *
  22211. * @param {Object3D} object - The 3D object that is going to be rendered.
  22212. * @param {number} count - The vertex or index count.
  22213. * @param {number} instanceCount - The instance count.
  22214. */
  22215. update( object, count, instanceCount ) {
  22216. this.render.drawCalls ++;
  22217. if ( object.isMesh || object.isSprite ) {
  22218. this.render.triangles += instanceCount * ( count / 3 );
  22219. } else if ( object.isPoints ) {
  22220. this.render.points += instanceCount * count;
  22221. } else if ( object.isLineSegments ) {
  22222. this.render.lines += instanceCount * ( count / 2 );
  22223. } else if ( object.isLine ) {
  22224. this.render.lines += instanceCount * ( count - 1 );
  22225. } else {
  22226. error( 'WebGPUInfo: Unknown object type.' );
  22227. }
  22228. }
  22229. /**
  22230. * Resets frame related metrics.
  22231. */
  22232. reset() {
  22233. this.render.drawCalls = 0;
  22234. this.render.frameCalls = 0;
  22235. this.compute.frameCalls = 0;
  22236. this.render.triangles = 0;
  22237. this.render.points = 0;
  22238. this.render.lines = 0;
  22239. }
  22240. /**
  22241. * Performs a complete reset of the object.
  22242. */
  22243. dispose() {
  22244. this.reset();
  22245. this.calls = 0;
  22246. this.render.calls = 0;
  22247. this.compute.calls = 0;
  22248. this.render.timestamp = 0;
  22249. this.compute.timestamp = 0;
  22250. for ( const prop in this.memory ) {
  22251. this.memory[ prop ] = 0;
  22252. }
  22253. this.memoryMap.clear();
  22254. }
  22255. /**
  22256. * Tracks texture memory explicitly, updating counts and byte tracking.
  22257. *
  22258. * @param {Texture} texture
  22259. */
  22260. createTexture( texture ) {
  22261. const size = this._getTextureMemorySize( texture );
  22262. this.memoryMap.set( texture, size );
  22263. this.memory.textures ++;
  22264. this.memory.total += size;
  22265. this.memory.texturesSize += size;
  22266. }
  22267. /**
  22268. * Tracks texture memory explicitly, updating counts and byte tracking.
  22269. *
  22270. * @param {Texture} texture
  22271. */
  22272. destroyTexture( texture ) {
  22273. const size = this.memoryMap.get( texture ) || 0;
  22274. this.memoryMap.delete( texture );
  22275. this.memory.textures --;
  22276. this.memory.total -= size;
  22277. this.memory.texturesSize -= size;
  22278. }
  22279. /**
  22280. * Tracks attribute memory explicitly, updating counts and byte tracking.
  22281. *
  22282. * @param {BufferAttribute} attribute
  22283. * @param {string} type - type of attribute
  22284. * @private
  22285. */
  22286. _createAttribute( attribute, type ) {
  22287. const size = this._getAttributeMemorySize( attribute );
  22288. this.memoryMap.set( attribute, { size, type } );
  22289. this.memory[ type ] ++;
  22290. this.memory.total += size;
  22291. this.memory[ type + 'Size' ] += size;
  22292. }
  22293. /**
  22294. * Tracks a regular attribute memory explicitly.
  22295. *
  22296. * @param {BufferAttribute} attribute - The attribute to track.
  22297. */
  22298. createAttribute( attribute ) {
  22299. this._createAttribute( attribute, 'attributes' );
  22300. }
  22301. /**
  22302. * Tracks an index attribute memory explicitly.
  22303. *
  22304. * @param {BufferAttribute} attribute - The index attribute to track.
  22305. */
  22306. createIndexAttribute( attribute ) {
  22307. this._createAttribute( attribute, 'indexAttributes' );
  22308. }
  22309. /**
  22310. * Tracks a storage attribute memory explicitly.
  22311. *
  22312. * @param {BufferAttribute} attribute - The storage attribute to track.
  22313. */
  22314. createStorageAttribute( attribute ) {
  22315. this._createAttribute( attribute, 'storageAttributes' );
  22316. }
  22317. /**
  22318. * Tracks an indirect storage attribute memory explicitly.
  22319. *
  22320. * @param {BufferAttribute} attribute - The indirect storage attribute to track.
  22321. */
  22322. createIndirectStorageAttribute( attribute ) {
  22323. this._createAttribute( attribute, 'indirectStorageAttributes' );
  22324. }
  22325. /**
  22326. * Tracks attribute memory explicitly, updating counts and byte tracking.
  22327. *
  22328. * @param {BufferAttribute} attribute
  22329. */
  22330. destroyAttribute( attribute ) {
  22331. const data = this.memoryMap.get( attribute );
  22332. if ( data ) {
  22333. this.memoryMap.delete( attribute );
  22334. this.memory[ data.type ] --;
  22335. this.memory.total -= data.size;
  22336. this.memory[ data.type + 'Size' ] -= data.size;
  22337. }
  22338. }
  22339. /**
  22340. * Tracks a readback buffer memory explicitly.
  22341. *
  22342. * @param {ReadbackBuffer} readbackBuffer - The readback buffer to track.
  22343. */
  22344. createReadbackBuffer( readbackBuffer ) {
  22345. const maxByteLength = readbackBuffer.maxByteLength;
  22346. this.memoryMap.set( readbackBuffer, { size: maxByteLength, type: 'readbackBuffers' } );
  22347. this.memory.readbackBuffers ++;
  22348. this.memory.total += maxByteLength;
  22349. this.memory.readbackBuffersSize += maxByteLength;
  22350. }
  22351. /**
  22352. * Tracks a readback buffer memory explicitly.
  22353. *
  22354. * @param {ReadbackBuffer} readbackBuffer - The readback buffer to track.
  22355. */
  22356. destroyReadbackBuffer( readbackBuffer ) {
  22357. const { size } = this.memoryMap.get( readbackBuffer );
  22358. this.memoryMap.delete( readbackBuffer );
  22359. this.memory.readbackBuffers --;
  22360. this.memory.total -= size;
  22361. this.memory.readbackBuffersSize -= size;
  22362. }
  22363. /**
  22364. * Tracks a uniform buffer memory explicitly.
  22365. *
  22366. * @param {UniformBuffer} uniformBuffer - The uniform buffer to track.
  22367. */
  22368. createUniformBuffer( uniformBuffer ) {
  22369. const size = uniformBuffer.byteLength;
  22370. this.memoryMap.set( uniformBuffer, { size, type: 'uniformBuffers' } );
  22371. this.memory.uniformBuffers ++;
  22372. this.memory.total += size;
  22373. this.memory.uniformBuffersSize += size;
  22374. }
  22375. /**
  22376. * Tracks a uniform buffer memory explicitly.
  22377. *
  22378. * @param {UniformBuffer} uniformBuffer - The uniform buffer to track.
  22379. */
  22380. destroyUniformBuffer( uniformBuffer ) {
  22381. const data = this.memoryMap.get( uniformBuffer );
  22382. if ( data ) {
  22383. this.memoryMap.delete( uniformBuffer );
  22384. this.memory.uniformBuffers --;
  22385. this.memory.total -= data.size;
  22386. this.memory.uniformBuffersSize -= data.size;
  22387. }
  22388. }
  22389. /**
  22390. * Tracks program memory explicitly, updating counts and byte tracking.
  22391. *
  22392. * @param {ProgrammableStage} program - The program to track.
  22393. */
  22394. createProgram( program ) {
  22395. const size = program.code.length; // Approx size
  22396. this.memoryMap.set( program, size );
  22397. this.memory.programs ++;
  22398. this.memory.total += size;
  22399. this.memory.programsSize += size;
  22400. }
  22401. /**
  22402. * Tracks program memory explicitly, updating counts and byte tracking.
  22403. *
  22404. * @param {Object} program - The program to track.
  22405. */
  22406. destroyProgram( program ) {
  22407. const size = this.memoryMap.get( program ) || 0;
  22408. this.memoryMap.delete( program );
  22409. this.memory.programs --;
  22410. this.memory.total -= size;
  22411. this.memory.programsSize -= size;
  22412. }
  22413. /**
  22414. * Calculates the memory size of a texture in bytes.
  22415. *
  22416. * @param {Texture} texture - The texture to calculate the size for.
  22417. * @return {number} The calculated size in bytes.
  22418. * @private
  22419. */
  22420. _getTextureMemorySize( texture ) {
  22421. if ( texture.isCompressedTexture ) {
  22422. return 1; // Fallback estimate since exact format decompressed isn't readily available without format maps
  22423. }
  22424. let bytesPerChannel = 1;
  22425. if ( texture.type === ByteType || texture.type === UnsignedByteType ) bytesPerChannel = 1;
  22426. else if ( texture.type === ShortType || texture.type === UnsignedShortType || texture.type === HalfFloatType ) bytesPerChannel = 2;
  22427. else if ( texture.type === IntType || texture.type === UnsignedIntType || texture.type === FloatType ) bytesPerChannel = 4;
  22428. let channels = 4; // RGBA default
  22429. if ( texture.format === AlphaFormat || texture.format === RedFormat || texture.format === RedIntegerFormat || texture.format === DepthFormat || texture.format === DepthStencilFormat ) channels = 1;
  22430. else if ( texture.format === RGFormat || texture.format === RGIntegerFormat ) channels = 2;
  22431. else if ( texture.format === RGBFormat || texture.format === RGBIntegerFormat ) channels = 3;
  22432. let bytesPerPixel = bytesPerChannel * channels;
  22433. // Packed overrides
  22434. if ( texture.type === UnsignedShort4444Type || texture.type === UnsignedShort5551Type ) bytesPerPixel = 2;
  22435. else if ( texture.type === UnsignedInt248Type || texture.type === UnsignedInt5999Type || texture.type === UnsignedInt101111Type ) bytesPerPixel = 4;
  22436. const width = texture.width || 1;
  22437. const height = texture.height || 1;
  22438. const depth = texture.isCubeTexture ? 6 : ( texture.depth || 1 );
  22439. let size = width * height * depth * bytesPerPixel;
  22440. const mipmaps = texture.mipmaps;
  22441. if ( mipmaps && mipmaps.length > 0 ) {
  22442. let mipmapSize = 0;
  22443. for ( let i = 0; i < mipmaps.length; i ++ ) {
  22444. const mipmap = mipmaps[ i ];
  22445. if ( mipmap.data ) {
  22446. mipmapSize += mipmap.data.byteLength;
  22447. } else {
  22448. const mipWidth = mipmap.width || Math.max( 1, width >> i );
  22449. const mipHeight = mipmap.height || Math.max( 1, height >> i );
  22450. mipmapSize += mipWidth * mipHeight * depth * bytesPerPixel;
  22451. }
  22452. }
  22453. size += mipmapSize;
  22454. } else if ( texture.generateMipmaps ) {
  22455. size = size * 1.333; // MiP chain approximation
  22456. }
  22457. return Math.round( size );
  22458. }
  22459. /**
  22460. * Calculates the memory size of an attribute in bytes.
  22461. *
  22462. * @param {BufferAttribute} attribute - The attribute to calculate the size for.
  22463. * @return {number} The calculated size in bytes.
  22464. * @private
  22465. */
  22466. _getAttributeMemorySize( attribute ) {
  22467. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  22468. if ( attribute.array ) {
  22469. return attribute.array.byteLength;
  22470. } else if ( attribute.count && attribute.itemSize ) {
  22471. return attribute.count * attribute.itemSize * 4; // Assume Float32
  22472. }
  22473. return 0;
  22474. }
  22475. }
  22476. /**
  22477. * Abstract class for representing pipelines.
  22478. *
  22479. * @private
  22480. * @abstract
  22481. */
  22482. class Pipeline {
  22483. /**
  22484. * Constructs a new pipeline.
  22485. *
  22486. * @param {string} cacheKey - The pipeline's cache key.
  22487. */
  22488. constructor( cacheKey ) {
  22489. /**
  22490. * The pipeline's cache key.
  22491. *
  22492. * @type {string}
  22493. */
  22494. this.cacheKey = cacheKey;
  22495. /**
  22496. * How often the pipeline is currently in use.
  22497. *
  22498. * @type {number}
  22499. * @default 0
  22500. */
  22501. this.usedTimes = 0;
  22502. }
  22503. }
  22504. /**
  22505. * Class for representing render pipelines.
  22506. *
  22507. * @private
  22508. * @augments Pipeline
  22509. */
  22510. class RenderObjectPipeline extends Pipeline {
  22511. /**
  22512. * Constructs a new render object pipeline.
  22513. *
  22514. * @param {string} cacheKey - The pipeline's cache key.
  22515. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  22516. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  22517. */
  22518. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  22519. super( cacheKey );
  22520. /**
  22521. * The pipeline's vertex shader.
  22522. *
  22523. * @type {ProgrammableStage}
  22524. */
  22525. this.vertexProgram = vertexProgram;
  22526. /**
  22527. * The pipeline's fragment shader.
  22528. *
  22529. * @type {ProgrammableStage}
  22530. */
  22531. this.fragmentProgram = fragmentProgram;
  22532. }
  22533. }
  22534. /**
  22535. * Class for representing compute pipelines.
  22536. *
  22537. * @private
  22538. * @augments Pipeline
  22539. */
  22540. class ComputePipeline extends Pipeline {
  22541. /**
  22542. * Constructs a new compute pipeline.
  22543. *
  22544. * @param {string} cacheKey - The pipeline's cache key.
  22545. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  22546. */
  22547. constructor( cacheKey, computeProgram ) {
  22548. super( cacheKey );
  22549. /**
  22550. * The pipeline's compute shader.
  22551. *
  22552. * @type {ProgrammableStage}
  22553. */
  22554. this.computeProgram = computeProgram;
  22555. /**
  22556. * This flag can be used for type testing.
  22557. *
  22558. * @type {boolean}
  22559. * @readonly
  22560. * @default true
  22561. */
  22562. this.isComputePipeline = true;
  22563. }
  22564. }
  22565. let _id$9 = 0;
  22566. /**
  22567. * Class for representing programmable stages which are vertex,
  22568. * fragment or compute shaders. Unlike fixed-function states (like blending),
  22569. * they represent the programmable part of a pipeline.
  22570. *
  22571. * @private
  22572. */
  22573. class ProgrammableStage {
  22574. /**
  22575. * Constructs a new programmable stage.
  22576. *
  22577. * @param {string} code - The shader code.
  22578. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  22579. * @param {string} name - The name of the shader.
  22580. * @param {?Array<Object>} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  22581. * @param {?Array<Object>} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  22582. */
  22583. constructor( code, stage, name, transforms = null, attributes = null ) {
  22584. /**
  22585. * The id of the programmable stage.
  22586. *
  22587. * @type {number}
  22588. */
  22589. this.id = _id$9 ++;
  22590. /**
  22591. * The shader code.
  22592. *
  22593. * @type {string}
  22594. */
  22595. this.code = code;
  22596. /**
  22597. * The type of stage.
  22598. *
  22599. * @type {string}
  22600. */
  22601. this.stage = stage;
  22602. /**
  22603. * The name of the stage.
  22604. * This is used for debugging purposes.
  22605. *
  22606. * @type {string}
  22607. */
  22608. this.name = name;
  22609. /**
  22610. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  22611. *
  22612. * @type {?Array<Object>}
  22613. */
  22614. this.transforms = transforms;
  22615. /**
  22616. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  22617. *
  22618. * @type {?Array<Object>}
  22619. */
  22620. this.attributes = attributes;
  22621. /**
  22622. * How often the programmable stage is currently in use.
  22623. *
  22624. * @type {number}
  22625. * @default 0
  22626. */
  22627. this.usedTimes = 0;
  22628. }
  22629. }
  22630. /**
  22631. * This renderer module manages the pipelines of the renderer.
  22632. *
  22633. * @private
  22634. * @augments DataMap
  22635. */
  22636. class Pipelines extends DataMap {
  22637. /**
  22638. * Constructs a new pipeline management component.
  22639. *
  22640. * @param {Backend} backend - The renderer's backend.
  22641. * @param {NodeManager} nodes - Renderer component for managing nodes related logic.
  22642. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  22643. */
  22644. constructor( backend, nodes, info ) {
  22645. super();
  22646. /**
  22647. * The renderer's backend.
  22648. *
  22649. * @type {Backend}
  22650. */
  22651. this.backend = backend;
  22652. /**
  22653. * Renderer component for managing nodes related logic.
  22654. *
  22655. * @type {NodeManager}
  22656. */
  22657. this.nodes = nodes;
  22658. /**
  22659. * Renderer component for managing metrics and monitoring data.
  22660. *
  22661. * @type {Info}
  22662. */
  22663. this.info = info;
  22664. /**
  22665. * A references to the bindings management component.
  22666. * This reference will be set inside the `Bindings`
  22667. * constructor.
  22668. *
  22669. * @type {?Bindings}
  22670. * @default null
  22671. */
  22672. this.bindings = null;
  22673. /**
  22674. * Internal cache for maintaining pipelines.
  22675. * The key of the map is a cache key, the value the pipeline.
  22676. *
  22677. * @type {Map<string,Pipeline>}
  22678. */
  22679. this.caches = new Map();
  22680. /**
  22681. * This dictionary maintains for each shader stage type (vertex,
  22682. * fragment and compute) the programmable stage objects which
  22683. * represent the actual shader code.
  22684. *
  22685. * @type {Object<string,Map<string, ProgrammableStage>>}
  22686. */
  22687. this.programs = {
  22688. vertex: new Map(),
  22689. fragment: new Map(),
  22690. compute: new Map()
  22691. };
  22692. }
  22693. /**
  22694. * Returns a compute pipeline for the given compute node.
  22695. *
  22696. * @param {Node} computeNode - The compute node.
  22697. * @param {Array<BindGroup>} bindings - The bindings.
  22698. * @return {ComputePipeline} The compute pipeline.
  22699. */
  22700. getForCompute( computeNode, bindings ) {
  22701. const { backend } = this;
  22702. const data = this.get( computeNode );
  22703. if ( this._needsComputeUpdate( computeNode ) ) {
  22704. const previousPipeline = data.pipeline;
  22705. if ( previousPipeline ) {
  22706. previousPipeline.usedTimes --;
  22707. previousPipeline.computeProgram.usedTimes --;
  22708. }
  22709. // get shader
  22710. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  22711. // programmable stage
  22712. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  22713. if ( stageCompute === undefined ) {
  22714. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  22715. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  22716. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  22717. backend.createProgram( stageCompute );
  22718. this.info.createProgram( stageCompute );
  22719. }
  22720. // determine compute pipeline
  22721. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  22722. let pipeline = this.caches.get( cacheKey );
  22723. if ( pipeline === undefined ) {
  22724. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  22725. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  22726. }
  22727. // keep track of all used times
  22728. pipeline.usedTimes ++;
  22729. stageCompute.usedTimes ++;
  22730. //
  22731. data.version = computeNode.version;
  22732. data.pipeline = pipeline;
  22733. }
  22734. return data.pipeline;
  22735. }
  22736. /**
  22737. * Returns a render pipeline for the given render object.
  22738. *
  22739. * @param {RenderObject} renderObject - The render object.
  22740. * @param {?Array<Promise>} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  22741. * @return {RenderObjectPipeline} The render pipeline.
  22742. */
  22743. getForRender( renderObject, promises = null ) {
  22744. const { backend } = this;
  22745. const data = this.get( renderObject );
  22746. if ( this._needsRenderUpdate( renderObject ) ) {
  22747. const previousPipeline = data.pipeline;
  22748. if ( previousPipeline ) {
  22749. previousPipeline.usedTimes --;
  22750. previousPipeline.vertexProgram.usedTimes --;
  22751. previousPipeline.fragmentProgram.usedTimes --;
  22752. }
  22753. // get shader
  22754. const nodeBuilderState = renderObject.getNodeBuilderState();
  22755. const name = renderObject.material ? renderObject.material.name : '';
  22756. // programmable stages
  22757. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  22758. if ( stageVertex === undefined ) {
  22759. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  22760. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  22761. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  22762. backend.createProgram( stageVertex );
  22763. this.info.createProgram( stageVertex );
  22764. }
  22765. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  22766. if ( stageFragment === undefined ) {
  22767. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  22768. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  22769. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  22770. backend.createProgram( stageFragment );
  22771. this.info.createProgram( stageFragment );
  22772. }
  22773. // determine render pipeline
  22774. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  22775. let pipeline = this.caches.get( cacheKey );
  22776. if ( pipeline === undefined ) {
  22777. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  22778. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  22779. } else {
  22780. renderObject.pipeline = pipeline;
  22781. }
  22782. // keep track of all used times
  22783. pipeline.usedTimes ++;
  22784. stageVertex.usedTimes ++;
  22785. stageFragment.usedTimes ++;
  22786. //
  22787. data.pipeline = pipeline;
  22788. }
  22789. return data.pipeline;
  22790. }
  22791. /**
  22792. * Checks if the render pipeline for the given render object is ready for drawing.
  22793. * Returns false if the GPU pipeline is still being compiled asynchronously.
  22794. *
  22795. * @param {RenderObject} renderObject - The render object.
  22796. * @return {boolean} True if the pipeline is ready for drawing.
  22797. */
  22798. isReady( renderObject ) {
  22799. const data = this.get( renderObject );
  22800. const pipeline = data.pipeline;
  22801. if ( pipeline === undefined ) return false;
  22802. const pipelineData = this.backend.get( pipeline );
  22803. return pipelineData.pipeline !== undefined && pipelineData.pipeline !== null;
  22804. }
  22805. /**
  22806. * Deletes the pipeline for the given render object.
  22807. *
  22808. * @param {RenderObject} object - The render object.
  22809. * @return {?Object} The deleted dictionary.
  22810. */
  22811. delete( object ) {
  22812. const pipeline = this.get( object ).pipeline;
  22813. if ( pipeline ) {
  22814. // pipeline
  22815. pipeline.usedTimes --;
  22816. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  22817. // programs
  22818. if ( pipeline.isComputePipeline ) {
  22819. pipeline.computeProgram.usedTimes --;
  22820. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  22821. } else {
  22822. pipeline.fragmentProgram.usedTimes --;
  22823. pipeline.vertexProgram.usedTimes --;
  22824. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  22825. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  22826. }
  22827. }
  22828. return super.delete( object );
  22829. }
  22830. /**
  22831. * Frees internal resources.
  22832. */
  22833. dispose() {
  22834. super.dispose();
  22835. this.caches = new Map();
  22836. this.programs = {
  22837. vertex: new Map(),
  22838. fragment: new Map(),
  22839. compute: new Map()
  22840. };
  22841. }
  22842. /**
  22843. * Updates the pipeline for the given render object.
  22844. *
  22845. * @param {RenderObject} renderObject - The render object.
  22846. */
  22847. updateForRender( renderObject ) {
  22848. this.getForRender( renderObject );
  22849. }
  22850. /**
  22851. * Returns a compute pipeline for the given parameters.
  22852. *
  22853. * @private
  22854. * @param {Node} computeNode - The compute node.
  22855. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  22856. * @param {string} cacheKey - The cache key.
  22857. * @param {Array<BindGroup>} bindings - The bindings.
  22858. * @return {ComputePipeline} The compute pipeline.
  22859. */
  22860. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  22861. // check for existing pipeline
  22862. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  22863. let pipeline = this.caches.get( cacheKey );
  22864. if ( pipeline === undefined ) {
  22865. pipeline = new ComputePipeline( cacheKey, stageCompute );
  22866. this.caches.set( cacheKey, pipeline );
  22867. this.backend.createComputePipeline( pipeline, bindings );
  22868. }
  22869. return pipeline;
  22870. }
  22871. /**
  22872. * Returns a render pipeline for the given parameters.
  22873. *
  22874. * @private
  22875. * @param {RenderObject} renderObject - The render object.
  22876. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  22877. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  22878. * @param {string} cacheKey - The cache key.
  22879. * @param {?Array<Promise>} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  22880. * @return {RenderObjectPipeline} The render pipeline.
  22881. */
  22882. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  22883. // check for existing pipeline
  22884. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  22885. let pipeline = this.caches.get( cacheKey );
  22886. if ( pipeline === undefined ) {
  22887. pipeline = new RenderObjectPipeline( cacheKey, stageVertex, stageFragment );
  22888. this.caches.set( cacheKey, pipeline );
  22889. renderObject.pipeline = pipeline;
  22890. // The `promises` array is `null` by default and only set to an empty array when
  22891. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  22892. // pending promises that resolve when the render pipelines are ready for rendering.
  22893. this.backend.createRenderPipeline( renderObject, promises );
  22894. }
  22895. return pipeline;
  22896. }
  22897. /**
  22898. * Computes a cache key representing a compute pipeline.
  22899. *
  22900. * @private
  22901. * @param {Node} computeNode - The compute node.
  22902. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  22903. * @return {string} The cache key.
  22904. */
  22905. _getComputeCacheKey( computeNode, stageCompute ) {
  22906. return computeNode.id + ',' + stageCompute.id;
  22907. }
  22908. /**
  22909. * Computes a cache key representing a render pipeline.
  22910. *
  22911. * @private
  22912. * @param {RenderObject} renderObject - The render object.
  22913. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  22914. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  22915. * @return {string} The cache key.
  22916. */
  22917. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  22918. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  22919. }
  22920. /**
  22921. * Releases the given pipeline.
  22922. *
  22923. * @private
  22924. * @param {Pipeline} pipeline - The pipeline to release.
  22925. */
  22926. _releasePipeline( pipeline ) {
  22927. this.caches.delete( pipeline.cacheKey );
  22928. }
  22929. /**
  22930. * Releases the shader program.
  22931. *
  22932. * @private
  22933. * @param {Object} program - The shader program to release.
  22934. */
  22935. _releaseProgram( program ) {
  22936. const code = program.code;
  22937. const stage = program.stage;
  22938. this.programs[ stage ].delete( code );
  22939. this.info.destroyProgram( program );
  22940. }
  22941. /**
  22942. * Returns `true` if the compute pipeline for the given compute node requires an update.
  22943. *
  22944. * @private
  22945. * @param {Node} computeNode - The compute node.
  22946. * @return {boolean} Whether the compute pipeline for the given compute node requires an update or not.
  22947. */
  22948. _needsComputeUpdate( computeNode ) {
  22949. const data = this.get( computeNode );
  22950. return data.pipeline === undefined || data.version !== computeNode.version;
  22951. }
  22952. /**
  22953. * Returns `true` if the render pipeline for the given render object requires an update.
  22954. *
  22955. * @private
  22956. * @param {RenderObject} renderObject - The render object.
  22957. * @return {boolean} Whether the render object for the given render object requires an update or not.
  22958. */
  22959. _needsRenderUpdate( renderObject ) {
  22960. const data = this.get( renderObject );
  22961. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  22962. }
  22963. }
  22964. /**
  22965. * This renderer module manages the bindings of the renderer.
  22966. *
  22967. * @private
  22968. * @augments DataMap
  22969. */
  22970. class Bindings extends DataMap {
  22971. /**
  22972. * Constructs a new bindings management component.
  22973. *
  22974. * @param {Backend} backend - The renderer's backend.
  22975. * @param {NodeManager} nodes - Renderer component for managing nodes related logic.
  22976. * @param {Textures} textures - Renderer component for managing textures.
  22977. * @param {Attributes} attributes - Renderer component for managing attributes.
  22978. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  22979. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  22980. */
  22981. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  22982. super();
  22983. /**
  22984. * The renderer's backend.
  22985. *
  22986. * @type {Backend}
  22987. */
  22988. this.backend = backend;
  22989. /**
  22990. * Renderer component for managing textures.
  22991. *
  22992. * @type {Textures}
  22993. */
  22994. this.textures = textures;
  22995. /**
  22996. * Renderer component for managing pipelines.
  22997. *
  22998. * @type {Pipelines}
  22999. */
  23000. this.pipelines = pipelines;
  23001. /**
  23002. * Renderer component for managing attributes.
  23003. *
  23004. * @type {Attributes}
  23005. */
  23006. this.attributes = attributes;
  23007. /**
  23008. * Renderer component for managing nodes related logic.
  23009. *
  23010. * @type {NodeManager}
  23011. */
  23012. this.nodes = nodes;
  23013. /**
  23014. * Renderer component for managing metrics and monitoring data.
  23015. *
  23016. * @type {Info}
  23017. */
  23018. this.info = info;
  23019. this.pipelines.bindings = this; // assign bindings to pipelines
  23020. }
  23021. /**
  23022. * Returns the bind groups for the given render object.
  23023. *
  23024. * @param {RenderObject} renderObject - The render object.
  23025. * @return {Array<BindGroup>} The bind groups.
  23026. */
  23027. getForRender( renderObject ) {
  23028. const bindings = renderObject.getBindings();
  23029. const renderObjectData = this.get( renderObject );
  23030. if ( renderObjectData.initialized !== true ) {
  23031. // bind groups are created once per object
  23032. this._createBindings( bindings );
  23033. renderObjectData.initialized = true;
  23034. }
  23035. return bindings;
  23036. }
  23037. /**
  23038. * Returns the bind groups for the given compute node.
  23039. *
  23040. * @param {Node} computeNode - The compute node.
  23041. * @return {Array<BindGroup>} The bind groups.
  23042. */
  23043. getForCompute( computeNode ) {
  23044. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  23045. const computeNodeData = this.get( computeNode );
  23046. if ( computeNodeData.initialized !== true || computeNodeData.bindings !== bindings ) {
  23047. // bind groups are created once per compute node version
  23048. if ( computeNodeData.bindings !== undefined ) {
  23049. this._destroyBindings( computeNodeData.bindings );
  23050. }
  23051. this._createBindings( bindings );
  23052. computeNodeData.initialized = true;
  23053. computeNodeData.bindings = bindings;
  23054. }
  23055. return bindings;
  23056. }
  23057. /**
  23058. * Updates the bindings for the given compute node.
  23059. *
  23060. * @param {Node} computeNode - The compute node.
  23061. */
  23062. updateForCompute( computeNode ) {
  23063. this._updateBindings( this.getForCompute( computeNode ) );
  23064. }
  23065. /**
  23066. * Updates the bindings for the given render object.
  23067. *
  23068. * @param {RenderObject} renderObject - The render object.
  23069. */
  23070. updateForRender( renderObject ) {
  23071. this._updateBindings( this.getForRender( renderObject ) );
  23072. }
  23073. /**
  23074. * Deletes the bindings for the given compute node.
  23075. *
  23076. * @param {Node} computeNode - The compute node.
  23077. */
  23078. deleteForCompute( computeNode ) {
  23079. const computeNodeData = this.get( computeNode );
  23080. const bindings = computeNodeData.bindings || this.nodes.getForCompute( computeNode ).bindings;
  23081. this._destroyBindings( bindings );
  23082. this.delete( computeNode );
  23083. }
  23084. /**
  23085. * Deletes the bindings for the given renderObject node.
  23086. *
  23087. * @param {RenderObject} renderObject - The renderObject.
  23088. */
  23089. deleteForRender( renderObject ) {
  23090. const bindings = renderObject.getBindings();
  23091. this._destroyBindings( bindings );
  23092. this.delete( renderObject );
  23093. }
  23094. /**
  23095. * Creates the bindings for the given array of bindings.
  23096. *
  23097. * @param {Array<BindGroup>} bindings - The bind groups.
  23098. */
  23099. _createBindings( bindings ) {
  23100. for ( const bindGroup of bindings ) {
  23101. // binding group
  23102. const groupData = this.get( bindGroup );
  23103. if ( groupData.bindGroup === undefined ) {
  23104. // initialize
  23105. for ( const binding of bindGroup.bindings ) {
  23106. if ( binding.isUniformBuffer ) {
  23107. this.backend.createUniformBuffer( binding );
  23108. this.info.createUniformBuffer( binding );
  23109. } else if ( binding.isSampledTexture ) {
  23110. this.textures.updateTexture( binding.texture );
  23111. } else if ( binding.isSampler ) {
  23112. this.textures.updateSampler( binding );
  23113. } else if ( binding.isStorageBuffer ) {
  23114. const attribute = binding.attribute;
  23115. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  23116. this.attributes.update( attribute, attributeType );
  23117. }
  23118. }
  23119. // each object defines an array of bindings (ubos, textures, samplers etc.)
  23120. this.backend.createBindings( bindGroup, bindings, 0 );
  23121. groupData.bindGroup = bindGroup;
  23122. groupData.usedTimes = 1;
  23123. } else {
  23124. groupData.usedTimes ++;
  23125. }
  23126. }
  23127. }
  23128. /**
  23129. * Deletes the given array of bindings.
  23130. *
  23131. * @param {Array<BindGroup>} bindings - The bind groups.
  23132. */
  23133. _destroyBindings( bindings ) {
  23134. for ( const bindGroup of bindings ) {
  23135. const groupData = this.get( bindGroup );
  23136. groupData.usedTimes --;
  23137. if ( groupData.usedTimes === 0 ) {
  23138. for ( const binding of bindGroup.bindings ) {
  23139. if ( binding.isUniformBuffer ) {
  23140. this.backend.destroyUniformBuffer( binding );
  23141. this.info.destroyUniformBuffer( binding );
  23142. // release arrays
  23143. binding.release();
  23144. } else if ( binding.isSampler ) {
  23145. if ( binding.isSampledTexture !== true ) {
  23146. this.backend.destroySampler( binding );
  23147. }
  23148. const textureData = this.textures.get( binding.texture );
  23149. if ( textureData.bindGroups !== undefined ) textureData.bindGroups.delete( bindGroup );
  23150. binding.release();
  23151. }
  23152. }
  23153. this.backend.deleteBindGroupData( bindGroup );
  23154. this.delete( bindGroup );
  23155. }
  23156. }
  23157. }
  23158. /**
  23159. * Updates the given array of bindings.
  23160. *
  23161. * @param {Array<BindGroup>} bindings - The bind groups.
  23162. */
  23163. _updateBindings( bindings ) {
  23164. for ( const bindGroup of bindings ) {
  23165. this._update( bindGroup, bindings );
  23166. }
  23167. }
  23168. /**
  23169. * Updates the given bind group.
  23170. *
  23171. * @param {BindGroup} bindGroup - The bind group to update.
  23172. * @param {Array<BindGroup>} bindings - The bind groups.
  23173. */
  23174. _update( bindGroup, bindings ) {
  23175. const { backend } = this;
  23176. let needsBindingsUpdate = false;
  23177. let cacheBindings = true;
  23178. let cacheIndex = 0;
  23179. let version = 0;
  23180. // iterate over all bindings and check if buffer updates or a new binding group is required
  23181. for ( const binding of bindGroup.bindings ) {
  23182. const updatedGroup = this.nodes.updateGroup( binding );
  23183. // every uniforms group is a uniform buffer. So if no update is required,
  23184. // we move one with the next binding. Otherwise the next if block will update the group.
  23185. if ( updatedGroup === false ) continue;
  23186. //
  23187. if ( binding.isStorageBuffer ) {
  23188. const attribute = binding.attribute;
  23189. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  23190. const bindingData = backend.get( binding );
  23191. this.attributes.update( attribute, attributeType );
  23192. if ( bindingData.attribute !== attribute ) {
  23193. bindingData.attribute = attribute;
  23194. needsBindingsUpdate = true;
  23195. }
  23196. }
  23197. if ( binding.isUniformBuffer ) {
  23198. const updated = binding.update();
  23199. if ( updated ) {
  23200. backend.updateBinding( binding );
  23201. }
  23202. } else if ( binding.isSampledTexture ) {
  23203. const updated = binding.update();
  23204. // get the texture data after the update, to sync the texture reference from node
  23205. const texture = binding.texture;
  23206. const texturesTextureData = this.textures.get( texture );
  23207. if ( updated ) {
  23208. // version: update the texture data or create a new one
  23209. this.textures.updateTexture( texture );
  23210. // generation: update the bindings if the binding refers to a different texture object
  23211. if ( binding.generation !== texturesTextureData.generation ) {
  23212. binding.generation = texturesTextureData.generation;
  23213. needsBindingsUpdate = true;
  23214. }
  23215. // keep track which bind groups refer to the current texture (this is needed for dispose)
  23216. texturesTextureData.bindGroups.add( bindGroup );
  23217. }
  23218. const textureData = backend.get( texture );
  23219. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  23220. cacheBindings = false;
  23221. } else {
  23222. cacheIndex = cacheIndex * 10 + texture.id;
  23223. version += texture.version;
  23224. }
  23225. if ( texture.isStorageTexture === true && texture.mipmapsAutoUpdate === true ) {
  23226. const textureData = this.get( texture );
  23227. if ( binding.store === true ) {
  23228. textureData.needsMipmap = true;
  23229. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  23230. this.backend.generateMipmaps( texture );
  23231. textureData.needsMipmap = false;
  23232. }
  23233. }
  23234. } else if ( binding.isSampler ) {
  23235. const updated = binding.update();
  23236. if ( updated ) {
  23237. const samplerKey = this.textures.updateSampler( binding );
  23238. if ( binding.samplerKey !== samplerKey ) {
  23239. binding.samplerKey = samplerKey;
  23240. needsBindingsUpdate = true;
  23241. }
  23242. }
  23243. }
  23244. if ( binding.isBuffer && binding.updateRanges.length > 0 ) {
  23245. binding.clearUpdateRanges();
  23246. }
  23247. }
  23248. if ( needsBindingsUpdate === true ) {
  23249. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  23250. }
  23251. }
  23252. }
  23253. const _emptyArray = /*@__PURE__*/ Object.freeze( [] );
  23254. /**
  23255. * Default sorting function for opaque render items.
  23256. *
  23257. * @private
  23258. * @function
  23259. * @param {Object} a - The first render item.
  23260. * @param {Object} b - The second render item.
  23261. * @return {number} A numeric value which defines the sort order.
  23262. */
  23263. function painterSortStable( a, b ) {
  23264. if ( a.groupOrder !== b.groupOrder ) {
  23265. return a.groupOrder - b.groupOrder;
  23266. } else if ( a.renderOrder !== b.renderOrder ) {
  23267. return a.renderOrder - b.renderOrder;
  23268. } else if ( a.z !== b.z ) {
  23269. return a.z - b.z;
  23270. } else {
  23271. return a.id - b.id;
  23272. }
  23273. }
  23274. /**
  23275. * Default sorting function for transparent render items.
  23276. *
  23277. * @private
  23278. * @function
  23279. * @param {Object} a - The first render item.
  23280. * @param {Object} b - The second render item.
  23281. * @return {number} A numeric value which defines the sort order.
  23282. */
  23283. function reversePainterSortStable( a, b ) {
  23284. if ( a.groupOrder !== b.groupOrder ) {
  23285. return a.groupOrder - b.groupOrder;
  23286. } else if ( a.renderOrder !== b.renderOrder ) {
  23287. return a.renderOrder - b.renderOrder;
  23288. } else if ( a.z !== b.z ) {
  23289. return b.z - a.z;
  23290. } else {
  23291. return a.id - b.id;
  23292. }
  23293. }
  23294. /**
  23295. * Returns `true` if the given transparent material requires a double pass.
  23296. *
  23297. * @private
  23298. * @function
  23299. * @param {Material} material - The transparent material.
  23300. * @return {boolean} Whether the given material requires a double pass or not.
  23301. */
  23302. function needsDoublePass( material ) {
  23303. const hasTransmission = material.transmission > 0 || ( material.transmissionNode && material.transmissionNode.isNode );
  23304. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  23305. }
  23306. /**
  23307. * When the renderer analyzes the scene at the beginning of a render call,
  23308. * it stores 3D object for further processing in render lists. Depending on the
  23309. * properties of a 3D objects (like their transformation or material state), the
  23310. * objects are maintained in ordered lists for the actual rendering.
  23311. *
  23312. * Render lists are unique per scene and camera combination.
  23313. *
  23314. * @private
  23315. * @augments Pipeline
  23316. */
  23317. class RenderList {
  23318. /**
  23319. * Constructs a render list.
  23320. *
  23321. * @param {Lighting} lighting - The lighting management component.
  23322. * @param {Scene} scene - The scene.
  23323. * @param {Camera} camera - The camera the scene is rendered with.
  23324. */
  23325. constructor( lighting, scene, camera ) {
  23326. /**
  23327. * 3D objects are transformed into render items and stored in this array.
  23328. *
  23329. * @type {Array<Object>}
  23330. */
  23331. this.renderItems = [];
  23332. /**
  23333. * The current render items index.
  23334. *
  23335. * @type {number}
  23336. * @default 0
  23337. */
  23338. this.renderItemsIndex = 0;
  23339. /**
  23340. * A list with opaque render items.
  23341. *
  23342. * @type {Array<Object>}
  23343. */
  23344. this.opaque = [];
  23345. /**
  23346. * A list with transparent render items which require
  23347. * double pass rendering (e.g. transmissive objects).
  23348. *
  23349. * @type {Array<Object>}
  23350. */
  23351. this.transparentDoublePass = [];
  23352. /**
  23353. * A list with transparent render items.
  23354. *
  23355. * @type {Array<Object>}
  23356. */
  23357. this.transparent = [];
  23358. /**
  23359. * A list with transparent render bundle data.
  23360. *
  23361. * @type {Array<Object>}
  23362. */
  23363. this.bundles = [];
  23364. /**
  23365. * The lighting management component.
  23366. *
  23367. * @type {Lighting}
  23368. */
  23369. this.lighting = lighting;
  23370. /**
  23371. * The render list's lights node. This node is later
  23372. * relevant for the actual analytical light nodes which
  23373. * compute the scene's lighting in the shader.
  23374. *
  23375. * @type {LightsNode}
  23376. */
  23377. this.lightsNode = lighting.getNode( scene );
  23378. /**
  23379. * The scene's lights stored in an array. This array
  23380. * is used to setup the lights node.
  23381. *
  23382. * @type {Array<Light>}
  23383. */
  23384. this.lightsArray = [];
  23385. /**
  23386. * The scene.
  23387. *
  23388. * @type {Scene}
  23389. */
  23390. this.scene = scene;
  23391. /**
  23392. * The camera the scene is rendered with.
  23393. *
  23394. * @type {Camera}
  23395. */
  23396. this.camera = camera;
  23397. /**
  23398. * How many objects perform occlusion query tests.
  23399. *
  23400. * @type {number}
  23401. * @default 0
  23402. */
  23403. this.occlusionQueryCount = 0;
  23404. /**
  23405. * The ID of the frame the render list was last used in.
  23406. *
  23407. * @type {number}
  23408. * @default -1
  23409. */
  23410. this.frameId = -1;
  23411. /**
  23412. * The last object that was counted for occlusion query testing. Used to
  23413. * avoid counting an object more than once when it produces multiple render
  23414. * items (e.g. a mesh with multiple material groups), since such an object
  23415. * is covered by a single occlusion query.
  23416. *
  23417. * @private
  23418. * @type {?Object3D}
  23419. * @default null
  23420. */
  23421. this._lastOcclusionObject = null;
  23422. }
  23423. /**
  23424. * This method is called right at the beginning of a render call
  23425. * before the scene is analyzed. It prepares the internal data
  23426. * structures for the upcoming render lists generation.
  23427. *
  23428. * @return {RenderList} A reference to this render list.
  23429. */
  23430. begin() {
  23431. this.renderItemsIndex = 0;
  23432. this.opaque.length = 0;
  23433. this.transparentDoublePass.length = 0;
  23434. this.transparent.length = 0;
  23435. this.bundles.length = 0;
  23436. this.lightsArray.length = 0;
  23437. this.occlusionQueryCount = 0;
  23438. return this;
  23439. }
  23440. /**
  23441. * Returns a render item for the giving render item state. The state is defined
  23442. * by a series of object-related parameters.
  23443. *
  23444. * The method avoids object creation by holding render items and reusing them in
  23445. * subsequent render calls (just with different property values).
  23446. *
  23447. * @param {Object3D} object - The 3D object.
  23448. * @param {BufferGeometry} geometry - The 3D object's geometry.
  23449. * @param {Material} material - The 3D object's material.
  23450. * @param {number} groupOrder - The current group order.
  23451. * @param {number} z - Th 3D object's depth value (z value in clip space).
  23452. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  23453. * @param {ClippingContext} clippingContext - The current clipping context.
  23454. * @return {Object} The render item.
  23455. */
  23456. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  23457. let renderItem = this.renderItems[ this.renderItemsIndex ];
  23458. if ( renderItem === undefined ) {
  23459. renderItem = {
  23460. id: object.id,
  23461. object: object,
  23462. geometry: geometry,
  23463. material: material,
  23464. groupOrder: groupOrder,
  23465. renderOrder: object.renderOrder,
  23466. z: z,
  23467. group: group,
  23468. clippingContext: clippingContext
  23469. };
  23470. this.renderItems[ this.renderItemsIndex ] = renderItem;
  23471. } else {
  23472. renderItem.id = object.id;
  23473. renderItem.object = object;
  23474. renderItem.geometry = geometry;
  23475. renderItem.material = material;
  23476. renderItem.groupOrder = groupOrder;
  23477. renderItem.renderOrder = object.renderOrder;
  23478. renderItem.z = z;
  23479. renderItem.group = group;
  23480. renderItem.clippingContext = clippingContext;
  23481. }
  23482. this.renderItemsIndex ++;
  23483. return renderItem;
  23484. }
  23485. /**
  23486. * Pushes the given object as a render item to the internal render lists.
  23487. * The selected lists depend on the object properties.
  23488. *
  23489. * @param {Object3D} object - The 3D object.
  23490. * @param {BufferGeometry} geometry - The 3D object's geometry.
  23491. * @param {Material} material - The 3D object's material.
  23492. * @param {number} groupOrder - The current group order.
  23493. * @param {number} z - Th 3D object's depth value (z value in clip space).
  23494. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  23495. * @param {ClippingContext} clippingContext - The current clipping context.
  23496. */
  23497. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  23498. // with a reversed depth buffer the projected z is inverted
  23499. if ( this.camera.reversedDepth === true ) z = - z;
  23500. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  23501. if ( object.occlusionTest === true && this._lastOcclusionObject !== object ) {
  23502. this.occlusionQueryCount ++;
  23503. this._lastOcclusionObject = object;
  23504. }
  23505. if ( material.transparent === true || material.transmission > 0 ||
  23506. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  23507. ( material.backdropNode && material.backdropNode.isNode ) ) {
  23508. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  23509. this.transparent.push( renderItem );
  23510. } else {
  23511. this.opaque.push( renderItem );
  23512. }
  23513. }
  23514. /**
  23515. * Inserts the given object as a render item at the start of the internal render lists.
  23516. * The selected lists depend on the object properties.
  23517. *
  23518. * @param {Object3D} object - The 3D object.
  23519. * @param {BufferGeometry} geometry - The 3D object's geometry.
  23520. * @param {Material} material - The 3D object's material.
  23521. * @param {number} groupOrder - The current group order.
  23522. * @param {number} z - Th 3D object's depth value (z value in clip space).
  23523. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  23524. * @param {ClippingContext} clippingContext - The current clipping context.
  23525. */
  23526. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  23527. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  23528. if ( material.transparent === true || material.transmission > 0 ||
  23529. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  23530. ( material.backdropNode && material.backdropNode.isNode ) ) {
  23531. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  23532. this.transparent.unshift( renderItem );
  23533. } else {
  23534. this.opaque.unshift( renderItem );
  23535. }
  23536. }
  23537. /**
  23538. * Pushes render bundle group data into the render list.
  23539. *
  23540. * @param {Object} group - Bundle group data.
  23541. */
  23542. pushBundle( group ) {
  23543. this.bundles.push( group );
  23544. }
  23545. /**
  23546. * Pushes a light into the render list.
  23547. *
  23548. * @param {Light} light - The light.
  23549. */
  23550. pushLight( light ) {
  23551. this.lightsArray.push( light );
  23552. }
  23553. /**
  23554. * Sorts the internal render lists.
  23555. *
  23556. * @param {?function(any, any): number} customOpaqueSort - A custom sort function for opaque objects.
  23557. * @param {?function(any, any): number} customTransparentSort - A custom sort function for transparent objects.
  23558. */
  23559. sort( customOpaqueSort, customTransparentSort ) {
  23560. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  23561. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  23562. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  23563. }
  23564. /**
  23565. * This method performs finalizing tasks right after the render lists
  23566. * have been generated.
  23567. */
  23568. finish() {
  23569. // update lights
  23570. this.lightsNode.setLights( this.lighting.enabled ? this.lightsArray : _emptyArray );
  23571. // Clear references from inactive renderItems in the list
  23572. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  23573. const renderItem = this.renderItems[ i ];
  23574. if ( renderItem.id === null ) break;
  23575. resetRenderItem( renderItem );
  23576. }
  23577. this._lastOcclusionObject = null;
  23578. }
  23579. /**
  23580. * This method is called when the render list has become inactive.
  23581. */
  23582. clear() {
  23583. // Clear all references from the render items so scene objects
  23584. // are not retained when the render list is not used anymore.
  23585. for ( let i = 0, il = this.renderItems.length; i < il; i ++ ) {
  23586. const renderItem = this.renderItems[ i ];
  23587. if ( renderItem.id === null ) break;
  23588. resetRenderItem( renderItem );
  23589. }
  23590. this.opaque.length = 0;
  23591. this.transparentDoublePass.length = 0;
  23592. this.transparent.length = 0;
  23593. this.bundles.length = 0;
  23594. }
  23595. }
  23596. function resetRenderItem( renderItem ) {
  23597. renderItem.id = null;
  23598. renderItem.object = null;
  23599. renderItem.geometry = null;
  23600. renderItem.material = null;
  23601. renderItem.groupOrder = null;
  23602. renderItem.renderOrder = null;
  23603. renderItem.z = null;
  23604. renderItem.group = null;
  23605. renderItem.clippingContext = null;
  23606. }
  23607. const _chainKeys$2 = [];
  23608. /**
  23609. * This renderer module manages the render lists which are unique
  23610. * per scene and camera combination.
  23611. *
  23612. * @private
  23613. */
  23614. class RenderLists {
  23615. /**
  23616. * Constructs a render lists management component.
  23617. *
  23618. * @param {Lighting} lighting - The lighting management component.
  23619. */
  23620. constructor( lighting ) {
  23621. /**
  23622. * The lighting management component.
  23623. *
  23624. * @type {Lighting}
  23625. */
  23626. this.lighting = lighting;
  23627. /**
  23628. * The internal chain map which holds the render lists.
  23629. *
  23630. * @type {ChainMap}
  23631. */
  23632. this.lists = new ChainMap();
  23633. /**
  23634. * The render lists which are currently in use. Lists are removed
  23635. * as soon as they become stale.
  23636. *
  23637. * @private
  23638. * @type {Set<RenderList>}
  23639. */
  23640. this._activeLists = new Set();
  23641. /**
  23642. * The current frame ID.
  23643. *
  23644. * @private
  23645. * @type {number}
  23646. */
  23647. this._frameId = -1;
  23648. }
  23649. /**
  23650. * Returns a render list for the given scene and camera.
  23651. *
  23652. * @param {Scene} scene - The scene.
  23653. * @param {Camera} camera - The camera.
  23654. * @return {RenderList} The render list.
  23655. */
  23656. get( scene, camera ) {
  23657. const lists = this.lists;
  23658. _chainKeys$2[ 0 ] = scene;
  23659. _chainKeys$2[ 1 ] = camera;
  23660. let list = lists.get( _chainKeys$2 );
  23661. if ( list === undefined ) {
  23662. list = new RenderList( this.lighting, scene, camera );
  23663. lists.set( _chainKeys$2, list );
  23664. }
  23665. _chainKeys$2[ 0 ] = null;
  23666. _chainKeys$2[ 1 ] = null;
  23667. //
  23668. list.frameId = this._frameId;
  23669. this._activeLists.add( list );
  23670. return list;
  23671. }
  23672. /**
  23673. * Must be called when a new frame begins.
  23674. *
  23675. * @param {number} frameId - The current frame ID.
  23676. */
  23677. update( frameId ) {
  23678. if ( frameId === this._frameId ) return;
  23679. this._frameId = frameId;
  23680. for ( const list of this._activeLists ) {
  23681. // if a render list has not been used within 10 frames, consider
  23682. // it as inactive and clear it
  23683. if ( frameId - list.frameId > 10 ) {
  23684. list.clear();
  23685. this._activeLists.delete( list );
  23686. }
  23687. }
  23688. }
  23689. /**
  23690. * Frees all internal resources.
  23691. */
  23692. dispose() {
  23693. this.lists = new ChainMap();
  23694. this._activeLists.clear();
  23695. this._frameId = -1;
  23696. }
  23697. }
  23698. let _id$8 = 0;
  23699. /**
  23700. * Any render or compute command is executed in a specific context that defines
  23701. * the state of the renderer and its backend. Typical examples for such context
  23702. * data are the current clear values or data from the active framebuffer. This
  23703. * module is used to represent these contexts as objects.
  23704. *
  23705. * @private
  23706. */
  23707. class RenderContext {
  23708. /**
  23709. * Constructs a new render context.
  23710. */
  23711. constructor() {
  23712. /**
  23713. * The context's ID.
  23714. *
  23715. * @type {number}
  23716. */
  23717. this.id = _id$8 ++;
  23718. /**
  23719. * The MRT configuration.
  23720. *
  23721. * @type {?MRTNode}
  23722. * @default null
  23723. */
  23724. this.mrt = null;
  23725. /**
  23726. * Whether the current active framebuffer has a color attachment.
  23727. *
  23728. * @type {boolean}
  23729. * @default true
  23730. */
  23731. this.color = true;
  23732. /**
  23733. * Whether the color attachment should be cleared or not.
  23734. *
  23735. * @type {boolean}
  23736. * @default true
  23737. */
  23738. this.clearColor = true;
  23739. /**
  23740. * The clear color value.
  23741. *
  23742. * @type {Object}
  23743. * @default true
  23744. */
  23745. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  23746. /**
  23747. * Whether the current active framebuffer has a depth attachment.
  23748. *
  23749. * @type {boolean}
  23750. * @default true
  23751. */
  23752. this.depth = true;
  23753. /**
  23754. * Whether the depth attachment should be cleared or not.
  23755. *
  23756. * @type {boolean}
  23757. * @default true
  23758. */
  23759. this.clearDepth = true;
  23760. /**
  23761. * The clear depth value.
  23762. *
  23763. * @type {number}
  23764. * @default 1
  23765. */
  23766. this.clearDepthValue = 1;
  23767. /**
  23768. * Whether the current active framebuffer has a stencil attachment.
  23769. *
  23770. * @type {boolean}
  23771. * @default false
  23772. */
  23773. this.stencil = false;
  23774. /**
  23775. * Whether the stencil attachment should be cleared or not.
  23776. *
  23777. * @type {boolean}
  23778. * @default true
  23779. */
  23780. this.clearStencil = true;
  23781. /**
  23782. * The clear stencil value.
  23783. *
  23784. * @type {number}
  23785. * @default 1
  23786. */
  23787. this.clearStencilValue = 1;
  23788. /**
  23789. * By default the viewport encloses the entire framebuffer If a smaller
  23790. * viewport is manually defined, this property is to `true` by the renderer.
  23791. *
  23792. * @type {boolean}
  23793. * @default false
  23794. */
  23795. this.viewport = false;
  23796. /**
  23797. * The viewport value. This value is in physical pixels meaning it incorporates
  23798. * the renderer's pixel ratio. The viewport property of render targets or
  23799. * the renderer is in logical pixels.
  23800. *
  23801. * @type {Vector4}
  23802. */
  23803. this.viewportValue = new Vector4();
  23804. /**
  23805. * When the scissor test is active and scissor rectangle smaller than the
  23806. * framebuffers dimensions, this property is to `true` by the renderer.
  23807. *
  23808. * @type {boolean}
  23809. * @default false
  23810. */
  23811. this.scissor = false;
  23812. /**
  23813. * The scissor rectangle.
  23814. *
  23815. * @type {Vector4}
  23816. */
  23817. this.scissorValue = new Vector4();
  23818. /**
  23819. * The active render target.
  23820. *
  23821. * @type {?RenderTarget}
  23822. * @default null
  23823. */
  23824. this.renderTarget = null;
  23825. /**
  23826. * The textures of the active render target.
  23827. * `null` when no render target is set.
  23828. *
  23829. * @type {?Array<Texture>}
  23830. * @default null
  23831. */
  23832. this.textures = null;
  23833. /**
  23834. * The depth texture of the active render target.
  23835. * `null` when no render target is set.
  23836. *
  23837. * @type {?DepthTexture}
  23838. * @default null
  23839. */
  23840. this.depthTexture = null;
  23841. /**
  23842. * The active cube face.
  23843. *
  23844. * @type {number}
  23845. * @default 0
  23846. */
  23847. this.activeCubeFace = 0;
  23848. /**
  23849. * The active mipmap level.
  23850. *
  23851. * @type {number}
  23852. * @default 0
  23853. */
  23854. this.activeMipmapLevel = 0;
  23855. /**
  23856. * The number of MSAA samples. This value is always `1` when
  23857. * MSAA isn't used.
  23858. *
  23859. * @type {number}
  23860. * @default 1
  23861. */
  23862. this.sampleCount = 1;
  23863. /**
  23864. * The active render target's width in physical pixels.
  23865. *
  23866. * @type {number}
  23867. * @default 0
  23868. */
  23869. this.width = 0;
  23870. /**
  23871. * The active render target's height in physical pixels.
  23872. *
  23873. * @type {number}
  23874. * @default 0
  23875. */
  23876. this.height = 0;
  23877. /**
  23878. * The occlusion query count.
  23879. *
  23880. * @type {number}
  23881. * @default 0
  23882. */
  23883. this.occlusionQueryCount = 0;
  23884. /**
  23885. * The current clipping context.
  23886. *
  23887. * @type {?ClippingContext}
  23888. * @default null
  23889. */
  23890. this.clippingContext = null;
  23891. /**
  23892. * The current camera.
  23893. *
  23894. * @type {?Camera}
  23895. * @default null
  23896. */
  23897. this.camera = null;
  23898. /**
  23899. * Whether a fullscreen pass is rendered or not.
  23900. *
  23901. * @type {boolean}
  23902. * @default false
  23903. */
  23904. this.fullscreenPass = false;
  23905. /**
  23906. * This flag can be used for type testing.
  23907. *
  23908. * @type {boolean}
  23909. * @readonly
  23910. * @default true
  23911. */
  23912. this.isRenderContext = true;
  23913. }
  23914. /**
  23915. * Returns the cache key of this render context.
  23916. *
  23917. * @return {number} The cache key.
  23918. */
  23919. getCacheKey() {
  23920. return getCacheKey( this );
  23921. }
  23922. }
  23923. /**
  23924. * Computes a cache key for the given render context. This key
  23925. * should identify the render target state so it is possible to
  23926. * configure the correct attachments in the respective backend.
  23927. *
  23928. * @param {RenderContext} renderContext - The render context.
  23929. * @return {number} The cache key.
  23930. */
  23931. function getCacheKey( renderContext ) {
  23932. const { textures, activeCubeFace, activeMipmapLevel } = renderContext;
  23933. const values = [ activeCubeFace, activeMipmapLevel ];
  23934. for ( const texture of textures ) {
  23935. values.push( texture.id );
  23936. }
  23937. return hashArray( values );
  23938. }
  23939. /**
  23940. * This module manages the render contexts of the renderer.
  23941. *
  23942. * @private
  23943. */
  23944. class RenderContexts {
  23945. /**
  23946. * Constructs a new render context management component.
  23947. *
  23948. * @param {Renderer} renderer - The renderer.
  23949. */
  23950. constructor( renderer ) {
  23951. /**
  23952. * The renderer.
  23953. *
  23954. * @type {Renderer}
  23955. */
  23956. this.renderer = renderer;
  23957. /**
  23958. * A dictionary that manages render contexts.
  23959. *
  23960. * @type {Object<string,RenderContext>}
  23961. */
  23962. this._renderContexts = {};
  23963. }
  23964. /**
  23965. * Returns a render context for the given scene, camera and render target.
  23966. *
  23967. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  23968. * @param {?MRTNode} [mrt=null] - The MRT configuration
  23969. * @param {?number} [callDepth=0] - The call depth of the renderer.
  23970. * @return {RenderContext} The render context.
  23971. */
  23972. get( renderTarget = null, mrt = null, callDepth = 0 ) {
  23973. //
  23974. let attachmentState;
  23975. if ( renderTarget === null ) {
  23976. attachmentState = 'default';
  23977. } else {
  23978. const format = renderTarget.texture.format;
  23979. const type = renderTarget.texture.type;
  23980. const count = renderTarget.textures.length;
  23981. attachmentState = `${ count }:${ format }:${ type }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  23982. }
  23983. //
  23984. const mrtState = ( mrt !== null ) ? mrt.id : 'default';
  23985. //
  23986. const renderStateKey = attachmentState + '-' + mrtState + '-' + callDepth;
  23987. let renderState = this._renderContexts[ renderStateKey ];
  23988. if ( renderState === undefined ) {
  23989. renderState = new RenderContext();
  23990. renderState.mrt = mrt;
  23991. this._renderContexts[ renderStateKey ] = renderState;
  23992. }
  23993. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  23994. renderState.clearDepthValue = this.renderer.getClearDepth();
  23995. renderState.clearStencilValue = this.renderer.getClearStencil();
  23996. return renderState;
  23997. }
  23998. /**
  23999. * Frees internal resources.
  24000. */
  24001. dispose() {
  24002. this._renderContexts = {};
  24003. }
  24004. }
  24005. const _size$3 = /*@__PURE__*/ new Vector3();
  24006. /**
  24007. * This module manages the textures of the renderer.
  24008. *
  24009. * @private
  24010. * @augments DataMap
  24011. */
  24012. class Textures extends DataMap {
  24013. /**
  24014. * Constructs a new texture management component.
  24015. *
  24016. * @param {Renderer} renderer - The renderer.
  24017. * @param {Backend} backend - The renderer's backend.
  24018. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  24019. */
  24020. constructor( renderer, backend, info ) {
  24021. super();
  24022. /**
  24023. * The renderer.
  24024. *
  24025. * @type {Renderer}
  24026. */
  24027. this.renderer = renderer;
  24028. /**
  24029. * The backend.
  24030. *
  24031. * @type {Backend}
  24032. */
  24033. this.backend = backend;
  24034. /**
  24035. * Renderer component for managing metrics and monitoring data.
  24036. *
  24037. * @type {Info}
  24038. */
  24039. this.info = info;
  24040. /**
  24041. * A set of HTMLTextures that need paint updates.
  24042. *
  24043. * @type {Set<HTMLTexture>}
  24044. */
  24045. this._htmlTextures = new Set();
  24046. }
  24047. /**
  24048. * Updates the given render target. Based on the given render target configuration,
  24049. * it updates the texture states representing the attachments of the framebuffer.
  24050. *
  24051. * @param {RenderTarget} renderTarget - The render target to update.
  24052. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  24053. */
  24054. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  24055. const renderTargetData = this.get( renderTarget );
  24056. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  24057. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  24058. const textures = renderTarget.textures;
  24059. const size = this.getSize( textures[ 0 ] );
  24060. const mipWidth = size.width >> activeMipmapLevel;
  24061. const mipHeight = size.height >> activeMipmapLevel;
  24062. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  24063. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  24064. let textureNeedsUpdate = false;
  24065. const hasArrayDepthTexture = depthTexture !== undefined && depthTexture.image !== undefined && depthTexture.image.depth > 1;
  24066. const useArrayDepth = size.depth > 1 && ( renderTarget.useArrayDepthTexture || renderTarget.multiview || hasArrayDepthTexture );
  24067. if ( depthTexture === undefined && useDepthTexture ) {
  24068. depthTexture = new DepthTexture();
  24069. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  24070. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  24071. depthTexture.image.width = mipWidth;
  24072. depthTexture.image.height = mipHeight;
  24073. depthTexture.image.depth = size.depth;
  24074. depthTexture.renderTarget = renderTarget;
  24075. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  24076. }
  24077. if ( depthTexture ) {
  24078. depthTexture.isArrayTexture = useArrayDepth;
  24079. }
  24080. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  24081. textureNeedsUpdate = true;
  24082. if ( depthTexture ) {
  24083. depthTexture.needsUpdate = true;
  24084. depthTexture.image.width = mipWidth;
  24085. depthTexture.image.height = mipHeight;
  24086. depthTexture.image.depth = useArrayDepth ? size.depth : 1;
  24087. }
  24088. }
  24089. renderTargetData.width = size.width;
  24090. renderTargetData.height = size.height;
  24091. renderTargetData.textures = textures;
  24092. renderTargetData.depthTexture = depthTexture || null;
  24093. renderTargetData.depth = renderTarget.depthBuffer;
  24094. renderTargetData.stencil = renderTarget.stencilBuffer;
  24095. renderTargetData.renderTarget = renderTarget;
  24096. if ( renderTargetData.sampleCount !== sampleCount ) {
  24097. textureNeedsUpdate = true;
  24098. if ( depthTexture ) {
  24099. depthTexture.needsUpdate = true;
  24100. }
  24101. renderTargetData.sampleCount = sampleCount;
  24102. }
  24103. //
  24104. const options = { sampleCount };
  24105. // XR render targets require no texture updates
  24106. if ( renderTarget.isXRRenderTarget !== true ) {
  24107. for ( let i = 0; i < textures.length; i ++ ) {
  24108. const texture = textures[ i ];
  24109. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  24110. this.updateTexture( texture, options );
  24111. }
  24112. if ( depthTexture ) {
  24113. this.updateTexture( depthTexture, options );
  24114. }
  24115. }
  24116. // dispose handler
  24117. if ( renderTargetData.initialized !== true ) {
  24118. renderTargetData.initialized = true;
  24119. this.info.memory.renderTargets ++;
  24120. // dispose
  24121. renderTargetData.onDispose = () => {
  24122. this._destroyRenderTarget( renderTarget );
  24123. };
  24124. renderTarget.addEventListener( 'dispose', renderTargetData.onDispose );
  24125. }
  24126. }
  24127. /**
  24128. * Updates the given texture. Depending on the texture state, this method
  24129. * triggers the upload of texture data to the GPU memory. If the texture data are
  24130. * not yet ready for the upload, it uses default texture data for as a placeholder.
  24131. *
  24132. * @param {Texture} texture - The texture to update.
  24133. * @param {Object} [options={}] - The options.
  24134. */
  24135. updateTexture( texture, options = {} ) {
  24136. const textureData = this.get( texture );
  24137. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  24138. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  24139. const backend = this.backend;
  24140. if ( isRenderTarget && textureData.initialized === true ) {
  24141. // it's an update
  24142. backend.destroyTexture( texture );
  24143. }
  24144. //
  24145. if ( texture.isFramebufferTexture ) {
  24146. const renderTarget = this.renderer.getRenderTarget();
  24147. if ( renderTarget ) {
  24148. texture.type = renderTarget.texture.type;
  24149. } else {
  24150. texture.type = UnsignedByteType;
  24151. }
  24152. }
  24153. // Ensure HTMLTexture elements are in the canvas before measuring size.
  24154. if ( texture.isHTMLTexture && texture.image ) {
  24155. const canvas = this.renderer.domElement;
  24156. if ( 'requestPaint' in canvas ) {
  24157. if ( ! canvas.hasAttribute( 'layoutsubtree' ) ) {
  24158. canvas.setAttribute( 'layoutsubtree', 'true' );
  24159. }
  24160. if ( texture.image.parentNode !== canvas ) {
  24161. canvas.appendChild( texture.image );
  24162. }
  24163. // Set up shared paint callback for all HTMLTextures.
  24164. if ( this._htmlTextures.size === 0 ) {
  24165. const htmlTextures = this._htmlTextures;
  24166. canvas.onpaint = ( event ) => {
  24167. const changed = event && event.changedElements;
  24168. for ( const t of htmlTextures ) {
  24169. if ( ! changed || changed.includes( t.image ) ) {
  24170. t.needsUpdate = true;
  24171. }
  24172. }
  24173. };
  24174. }
  24175. this._htmlTextures.add( texture );
  24176. }
  24177. }
  24178. //
  24179. const { width, height, depth } = this.getSize( texture );
  24180. options.width = width;
  24181. options.height = height;
  24182. options.depth = depth;
  24183. options.needsMipmaps = this.needsMipmaps( texture );
  24184. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  24185. // TODO: Uniformly handle mipmap definitions
  24186. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  24187. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  24188. if ( texture.isCubeTexture && texture.mipmaps.length > 0 ) options.levels ++;
  24189. //
  24190. if ( isRenderTarget || texture.isStorageTexture === true || texture.isExternalTexture === true ) {
  24191. backend.createTexture( texture, options );
  24192. textureData.generation = texture.version;
  24193. } else {
  24194. if ( texture.version > 0 ) {
  24195. const image = texture.image;
  24196. if ( image === undefined ) {
  24197. warn( 'Renderer: Texture marked for update but image is undefined.' );
  24198. } else if ( image.complete === false ) {
  24199. warn( 'Renderer: Texture marked for update but image is incomplete.' );
  24200. } else {
  24201. if ( texture.images ) {
  24202. const images = [];
  24203. for ( const image of texture.images ) {
  24204. images.push( image );
  24205. }
  24206. options.images = images;
  24207. } else {
  24208. options.image = image;
  24209. }
  24210. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  24211. backend.createTexture( texture, options );
  24212. textureData.isDefaultTexture = false;
  24213. textureData.generation = texture.version;
  24214. }
  24215. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  24216. const skipAutoGeneration = texture.isStorageTexture === true && texture.mipmapsAutoUpdate === false;
  24217. if ( options.needsMipmaps && texture.mipmaps.length === 0 && ! skipAutoGeneration ) {
  24218. backend.generateMipmaps( texture );
  24219. }
  24220. if ( texture.onUpdate ) texture.onUpdate( texture );
  24221. }
  24222. } else {
  24223. // async update
  24224. backend.createDefaultTexture( texture );
  24225. textureData.isDefaultTexture = true;
  24226. textureData.generation = texture.version;
  24227. }
  24228. }
  24229. // dispose handler
  24230. if ( textureData.initialized !== true ) {
  24231. textureData.initialized = true;
  24232. textureData.generation = texture.version;
  24233. textureData.bindGroups = new Set();
  24234. //
  24235. this.info.createTexture( texture );
  24236. //
  24237. if ( texture.isVideoTexture && ColorManagement.enabled === true && ColorManagement.getTransfer( texture.colorSpace ) !== SRGBTransfer ) {
  24238. warn( 'WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace.' );
  24239. }
  24240. // dispose
  24241. textureData.onDispose = () => {
  24242. this._destroyTexture( texture );
  24243. };
  24244. texture.addEventListener( 'dispose', textureData.onDispose );
  24245. }
  24246. //
  24247. textureData.version = texture.version;
  24248. }
  24249. /**
  24250. * Updates the sampler for the given texture. This method has no effect
  24251. * for the WebGL backend since it has no concept of samplers. Texture
  24252. * parameters are configured with the `texParameter()` command for each
  24253. * texture.
  24254. *
  24255. * In WebGPU, samplers are objects like textures and it's possible to share
  24256. * them when the texture parameters match.
  24257. *
  24258. * @param {Sampler} binding - The sampler binding to update.
  24259. * @return {string} The current sampler key.
  24260. */
  24261. updateSampler( binding ) {
  24262. return this.backend.updateSampler( binding );
  24263. }
  24264. /**
  24265. * Computes the size of the given texture and writes the result
  24266. * into the target vector. This vector is also returned by the
  24267. * method.
  24268. *
  24269. * If no texture data are available for the compute yet, the method
  24270. * returns default size values.
  24271. *
  24272. * @param {Texture} texture - The texture to compute the size for.
  24273. * @param {Vector3} target - The target vector.
  24274. * @return {Vector3} The target vector.
  24275. */
  24276. getSize( texture, target = _size$3 ) {
  24277. let image = texture.images ? texture.images[ 0 ] : texture.image;
  24278. if ( image ) {
  24279. if ( image.image !== undefined ) image = image.image;
  24280. if ( texture.isHTMLTexture ) {
  24281. target.width = image.offsetWidth || 1;
  24282. target.height = image.offsetHeight || 1;
  24283. target.depth = 1;
  24284. } else if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( image instanceof HTMLVideoElement ) ) {
  24285. target.width = image.videoWidth || 1;
  24286. target.height = image.videoHeight || 1;
  24287. target.depth = 1;
  24288. } else if ( ( typeof VideoFrame !== 'undefined' ) && ( image instanceof VideoFrame ) ) {
  24289. target.width = image.displayWidth || 1;
  24290. target.height = image.displayHeight || 1;
  24291. target.depth = 1;
  24292. } else {
  24293. target.width = image.width || 1;
  24294. target.height = image.height || 1;
  24295. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  24296. }
  24297. } else {
  24298. target.width = target.height = target.depth = 1;
  24299. }
  24300. return target;
  24301. }
  24302. /**
  24303. * Computes the number of mipmap levels for the given texture.
  24304. *
  24305. * @param {Texture} texture - The texture.
  24306. * @param {number} width - The texture's width.
  24307. * @param {number} height - The texture's height.
  24308. * @return {number} The number of mipmap levels.
  24309. */
  24310. getMipLevels( texture, width, height ) {
  24311. let mipLevelCount;
  24312. if ( texture.mipmaps.length > 0 ) {
  24313. mipLevelCount = texture.mipmaps.length;
  24314. } else {
  24315. if ( texture.isCompressedTexture === true ) {
  24316. // it is not possible to compute mipmaps for compressed textures. So
  24317. // when no mipmaps are defined in "texture.mipmaps", force a texture
  24318. // level of 1
  24319. mipLevelCount = 1;
  24320. } else {
  24321. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  24322. }
  24323. }
  24324. return mipLevelCount;
  24325. }
  24326. /**
  24327. * Returns `true` if the given texture makes use of mipmapping.
  24328. *
  24329. * @param {Texture} texture - The texture.
  24330. * @return {boolean} Whether mipmaps are required or not.
  24331. */
  24332. needsMipmaps( texture ) {
  24333. return texture.generateMipmaps === true || texture.mipmaps.length > 0;
  24334. }
  24335. /**
  24336. * Frees internal resources when the given render target isn't
  24337. * required anymore.
  24338. *
  24339. * @param {RenderTarget} renderTarget - The render target to destroy.
  24340. */
  24341. _destroyRenderTarget( renderTarget ) {
  24342. if ( this.has( renderTarget ) === true ) {
  24343. const renderTargetData = this.get( renderTarget );
  24344. const textures = renderTargetData.textures;
  24345. const depthTexture = renderTargetData.depthTexture;
  24346. //
  24347. renderTarget.removeEventListener( 'dispose', renderTargetData.onDispose );
  24348. //
  24349. for ( let i = 0; i < textures.length; i ++ ) {
  24350. this._destroyTexture( textures[ i ] );
  24351. }
  24352. if ( depthTexture ) {
  24353. this._destroyTexture( depthTexture );
  24354. }
  24355. this.delete( renderTarget );
  24356. this.backend.delete( renderTarget );
  24357. this.info.memory.renderTargets --;
  24358. }
  24359. }
  24360. /**
  24361. * Frees internal resource when the given texture isn't
  24362. * required anymore.
  24363. *
  24364. * @param {Texture} texture - The texture to destroy.
  24365. */
  24366. _destroyTexture( texture ) {
  24367. if ( this.has( texture ) === true ) {
  24368. const textureData = this.get( texture );
  24369. //
  24370. texture.removeEventListener( 'dispose', textureData.onDispose );
  24371. // if a texture is not ready for use, it falls back to a default texture so it's possible
  24372. // to use it for rendering. If a texture in this state is disposed, it's important to
  24373. // not destroy/delete the underlying GPU texture object since it is cached and shared with
  24374. // other textures.
  24375. const isDefaultTexture = textureData.isDefaultTexture;
  24376. this.backend.destroyTexture( texture, isDefaultTexture );
  24377. // delete cached bind groups so they don't point to destroyed textures
  24378. if ( textureData.bindGroups ) {
  24379. for ( const bindGroup of textureData.bindGroups ) {
  24380. const bindingsData = this.backend.get( bindGroup );
  24381. bindingsData.groups = undefined;
  24382. bindingsData.versions = undefined;
  24383. // go through all bindings and if one points to the destroyed texture, trigger dispose as well
  24384. for ( const binding of bindGroup.bindings ) {
  24385. if ( binding.isSampler && binding.texture === texture ) {
  24386. if ( binding.isSampledTexture !== true ) {
  24387. this.backend.destroySampler( binding );
  24388. }
  24389. binding.reset();
  24390. binding.release();
  24391. }
  24392. }
  24393. }
  24394. }
  24395. this._htmlTextures.delete( texture );
  24396. this.delete( texture );
  24397. this.info.destroyTexture( texture );
  24398. }
  24399. }
  24400. }
  24401. /**
  24402. * A four-component version of {@link Color} which is internally
  24403. * used by the renderer to represents clear color with alpha as
  24404. * one object.
  24405. *
  24406. * @private
  24407. * @augments Color
  24408. */
  24409. class Color4 extends Color {
  24410. /**
  24411. * Constructs a new four-component color.
  24412. * You can also pass a single THREE.Color, hex or
  24413. * string argument to this constructor.
  24414. *
  24415. * @param {number|string} [r=1] - The red value.
  24416. * @param {number} [g=1] - The green value.
  24417. * @param {number} [b=1] - The blue value.
  24418. * @param {number} [a=1] - The alpha value.
  24419. */
  24420. constructor( r, g, b, a = 1 ) {
  24421. super( r, g, b );
  24422. this.a = a;
  24423. }
  24424. /**
  24425. * Overwrites the default to honor alpha.
  24426. * You can also pass a single THREE.Color, hex or
  24427. * string argument to this method.
  24428. *
  24429. * @param {number|string|Color} r - The red value.
  24430. * @param {number} [g] - The green value.
  24431. * @param {number} [b] - The blue value.
  24432. * @param {number} [a=1] - The alpha value.
  24433. * @return {Color4} A reference to this object.
  24434. */
  24435. set( r, g, b, a = 1 ) {
  24436. this.a = a;
  24437. return super.set( r, g, b );
  24438. }
  24439. /**
  24440. * Overwrites the default to honor alpha.
  24441. *
  24442. * @param {Color4} color - The color to copy.
  24443. * @return {Color4} A reference to this object.
  24444. */
  24445. copy( color ) {
  24446. if ( color.a !== undefined ) this.a = color.a;
  24447. return super.copy( color );
  24448. }
  24449. /**
  24450. * Overwrites the default to honor alpha.
  24451. *
  24452. * @return {Color4} The cloned color.
  24453. */
  24454. clone() {
  24455. return new this.constructor( this.r, this.g, this.b, this.a );
  24456. }
  24457. }
  24458. /**
  24459. * A specialized context node designed to override specific target nodes within a
  24460. * node sub-graph or flow. This allows replacing specific inputs (e.g., normal
  24461. * and position vectors) dynamically during compilation for a specific flow node,
  24462. * without having to reconstruct or duplicate the source nodes.
  24463. *
  24464. * ```js
  24465. * // Method chaining example:
  24466. * node.overrideNode( positionLocal, () => positionLocal.add( vec3( 1, 0, 0 ) ) );
  24467. *
  24468. * // Context assignment example:
  24469. * material.contextNode = overrideNode( positionLocal, () => positionLocal.add( vec3( 1, 0, 0 ) ) );
  24470. * ```
  24471. *
  24472. * @augments ContextNode
  24473. */
  24474. class OverrideContextNode extends ContextNode {
  24475. /**
  24476. * Returns the type of the node.
  24477. *
  24478. * @type {string}
  24479. * @readonly
  24480. * @static
  24481. */
  24482. static get type() {
  24483. return 'OverrideContextNode';
  24484. }
  24485. /**
  24486. * Constructs a new override context node.
  24487. *
  24488. * @param {Map<Node, Function>} overrideNodes - A map mapping target nodes to their respective override callback functions.
  24489. * @param {Node|null} [flowNode=null] - The node whose context should be modified.
  24490. */
  24491. constructor( overrideNodes, flowNode = null ) {
  24492. super( flowNode, {
  24493. overrideNodes
  24494. } );
  24495. /**
  24496. * This flag can be used for type testing.
  24497. *
  24498. * @type {boolean}
  24499. * @readonly
  24500. * @default true
  24501. */
  24502. this.isOverrideContextNode = true;
  24503. }
  24504. /**
  24505. * Gathers the context data from all parent context nodes by traversing the hierarchy,
  24506. * merging the `overrideNodes` maps from all encountered `OverrideContextNode` instances.
  24507. *
  24508. * @return {Object} The gathered context data, containing the merged `overrideNodes` map.
  24509. */
  24510. getFlowContextData() {
  24511. const children = [];
  24512. this.traverse( ( node ) => {
  24513. if ( node.isOverrideContextNode === true ) {
  24514. children.push( node.value.overrideNodes );
  24515. }
  24516. } );
  24517. const overrideNodes = new Map( children.flatMap( ( map ) => Array.from( map.entries() ) ) );
  24518. const data = super.getFlowContextData();
  24519. data.overrideNodes = overrideNodes;
  24520. return data;
  24521. }
  24522. }
  24523. /**
  24524. * TSL function for creating an `OverrideContextNode` to override a single target node.
  24525. *
  24526. * ```js
  24527. * material.contextNode = overrideNode( positionLocal, ( builder ) => positionLocal.add( vec3( 1, 0, 0 ) ) );
  24528. * ```
  24529. *
  24530. * @tsl
  24531. * @function
  24532. * @param {Node} targetNode - The target node that should be overridden.
  24533. * @param {Function|Node|null} [callback=null] - A callback function returning the overriding node (which receives the builder as its argument), or the overriding node itself.
  24534. * @param {Node|null} [flowNode=null] - The node whose context should be modified.
  24535. * @return {OverrideContextNode} The created override context node.
  24536. */
  24537. function overrideNode( targetNode, callback = null, flowNode = null ) {
  24538. if ( callback && callback.isNode ) {
  24539. const node = callback;
  24540. callback = () => node;
  24541. }
  24542. return new OverrideContextNode( new Map( [[ targetNode, callback ]] ), flowNode );
  24543. }
  24544. addMethodChaining( 'overrideNode', ( flowNode, node, callback ) => overrideNode( node, callback, flowNode ) );
  24545. /**
  24546. * TSL function for creating an `OverrideContextNode` to override multiple target nodes.
  24547. *
  24548. * ```js
  24549. * material.contextNode = overrideNodes( [
  24550. * [ positionView, customPositionView ],
  24551. * [ positionViewDirection, ( builder ) => customPositionViewDirection ]
  24552. * ] );
  24553. * ```
  24554. *
  24555. * @tsl
  24556. * @function
  24557. * @param {Map<Node, (Function|Node)>|Array<Array<Node|Function|Node>>} overrides - The overrides mapping target nodes to callback functions or overriding nodes.
  24558. * @param {Node|null} [flowNode=null] - The node whose context should be modified.
  24559. * @return {OverrideContextNode} The created override context node.
  24560. */
  24561. function overrideNodes( overrides, flowNode = null ) {
  24562. const overrideNodesMap = new Map();
  24563. for ( const [ node, value ] of overrides ) {
  24564. const callback = value !== null ? typeof value === 'function' ? value : () => value : null;
  24565. overrideNodesMap.set( node, callback );
  24566. }
  24567. return new OverrideContextNode( overrideNodesMap, flowNode );
  24568. }
  24569. addMethodChaining( 'overrideNodes', ( flowNode, overrides ) => overrideNodes( overrides, flowNode ) );
  24570. /**
  24571. * Special version of {@link PropertyNode} which is used for parameters.
  24572. *
  24573. * @augments PropertyNode
  24574. */
  24575. class ParameterNode extends PropertyNode {
  24576. static get type() {
  24577. return 'ParameterNode';
  24578. }
  24579. /**
  24580. * Constructs a new parameter node.
  24581. *
  24582. * @param {string} nodeType - The type of the node.
  24583. * @param {?string} [name=null] - The name of the parameter in the shader.
  24584. */
  24585. constructor( nodeType, name = null ) {
  24586. super( nodeType, name );
  24587. /**
  24588. * This flag can be used for type testing.
  24589. *
  24590. * @type {boolean}
  24591. * @readonly
  24592. * @default true
  24593. */
  24594. this.isParameterNode = true;
  24595. }
  24596. /**
  24597. * Gets the type of a member variable in the parameter node.
  24598. *
  24599. * @param {NodeBuilder} builder - The node builder.
  24600. * @param {string} name - The name of the member variable.
  24601. * @returns {string}
  24602. */
  24603. getMemberType( builder, name ) {
  24604. const type = this.getNodeType( builder );
  24605. const struct = builder.getStructTypeNode( type );
  24606. let memberType;
  24607. if ( struct !== null ) {
  24608. memberType = struct.getMemberType( builder, name );
  24609. } else {
  24610. error( `TSL: Member "${ name }" not found in struct "${ type }".`, new StackTrace() );
  24611. memberType = 'float';
  24612. }
  24613. return memberType;
  24614. }
  24615. getHash() {
  24616. return String( this.id );
  24617. }
  24618. generate() {
  24619. return this.name;
  24620. }
  24621. }
  24622. /**
  24623. * TSL function for creating a parameter node.
  24624. *
  24625. * @tsl
  24626. * @function
  24627. * @param {string} type - The type of the node.
  24628. * @param {?string} name - The name of the parameter in the shader.
  24629. * @returns {ParameterNode}
  24630. */
  24631. const parameter = ( type, name ) => new ParameterNode( type, name );
  24632. /**
  24633. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  24634. * They are usually needed in cases like `If`, `Else`.
  24635. *
  24636. * @augments Node
  24637. */
  24638. class StackNode extends Node {
  24639. static get type() {
  24640. return 'StackNode';
  24641. }
  24642. /**
  24643. * Constructs a new stack node.
  24644. *
  24645. * @param {?StackNode} [parent=null] - The parent stack node.
  24646. */
  24647. constructor( parent = null ) {
  24648. super();
  24649. /**
  24650. * List of nodes.
  24651. *
  24652. * @type {Array<Node>}
  24653. */
  24654. this.nodes = [];
  24655. /**
  24656. * The output node.
  24657. *
  24658. * @type {?Node}
  24659. * @default null
  24660. */
  24661. this.outputNode = null;
  24662. /**
  24663. * The parent stack node.
  24664. *
  24665. * @type {?StackNode}
  24666. * @default null
  24667. */
  24668. this.parent = parent;
  24669. /**
  24670. * The current conditional node.
  24671. *
  24672. * @private
  24673. * @type {ConditionalNode}
  24674. * @default null
  24675. */
  24676. this._currentCond = null;
  24677. /**
  24678. * The expression node. Only
  24679. * relevant for Switch/Case.
  24680. *
  24681. * @private
  24682. * @type {Node}
  24683. * @default null
  24684. */
  24685. this._expressionNode = null;
  24686. /**
  24687. * The current node being processed.
  24688. *
  24689. * @private
  24690. * @type {Node}
  24691. * @default null
  24692. */
  24693. this._currentNode = null;
  24694. /**
  24695. * Stores additional data for nodes that are added to the stack.
  24696. *
  24697. * @private
  24698. * @type {Map<Node, {delta: number}>}
  24699. */
  24700. this._nodeDataLibrary = new Map();
  24701. /**
  24702. * This flag can be used for type testing.
  24703. *
  24704. * @type {boolean}
  24705. * @readonly
  24706. * @default true
  24707. */
  24708. this.isStackNode = true;
  24709. }
  24710. getElementType( builder ) {
  24711. return this.outputNode ? this.outputNode.getElementType( builder ) : 'void';
  24712. }
  24713. generateNodeType( builder ) {
  24714. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  24715. }
  24716. getMemberType( builder, name ) {
  24717. return this.outputNode ? this.outputNode.getMemberType( builder, name ) : 'void';
  24718. }
  24719. /**
  24720. * Adds a node to this stack.
  24721. *
  24722. * @param {Node} node - The node to add.
  24723. * @param {number} [index=-1] - The index of the node. If not specified, the node will be added to the end of the stack.
  24724. * @return {StackNode} A reference to this stack node.
  24725. */
  24726. addToStack( node, index = -1 ) {
  24727. if ( node.isNode !== true ) {
  24728. error( 'TSL: Invalid node added to stack.', new StackTrace() );
  24729. return this;
  24730. }
  24731. if ( index === -1 ) {
  24732. if ( this._currentNode ) {
  24733. let nodeData = this._nodeDataLibrary.get( this._currentNode );
  24734. if ( nodeData === undefined ) {
  24735. nodeData = {
  24736. delta: 0
  24737. };
  24738. this._nodeDataLibrary.set( this._currentNode, nodeData );
  24739. }
  24740. nodeData.delta ++;
  24741. index = this.nodes.indexOf( this._currentNode ) + nodeData.delta;
  24742. } else {
  24743. index = this.nodes.length;
  24744. }
  24745. }
  24746. this.nodes.splice( index, 0, node );
  24747. return this;
  24748. }
  24749. /**
  24750. * Adds a node to the stack before the current node.
  24751. *
  24752. * @param {Node} node - The node to add.
  24753. * @return {StackNode} A reference to this stack node.
  24754. */
  24755. addToStackBefore( node ) {
  24756. const index = this._currentNode ? this.nodes.indexOf( this._currentNode ) : 0;
  24757. return this.addToStack( node, index );
  24758. }
  24759. /**
  24760. * Represent an `if` statement in TSL.
  24761. *
  24762. * @param {Node} boolNode - Represents the condition.
  24763. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  24764. * @return {StackNode} A reference to this stack node.
  24765. */
  24766. If( boolNode, method ) {
  24767. const methodNode = new ShaderNode( method );
  24768. this._currentCond = select( boolNode, methodNode );
  24769. return this.addToStack( this._currentCond );
  24770. }
  24771. /**
  24772. * Represent an `elseif` statement in TSL.
  24773. *
  24774. * @param {Node} boolNode - Represents the condition.
  24775. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  24776. * @return {StackNode} A reference to this stack node.
  24777. */
  24778. ElseIf( boolNode, method ) {
  24779. const methodNode = new ShaderNode( method );
  24780. const ifNode = select( boolNode, methodNode );
  24781. this._currentCond.elseNode = ifNode;
  24782. this._currentCond = ifNode;
  24783. return this;
  24784. }
  24785. /**
  24786. * Represent an `else` statement in TSL.
  24787. *
  24788. * @param {Function} method - TSL code which is executed in the `else` case.
  24789. * @return {StackNode} A reference to this stack node.
  24790. */
  24791. Else( method ) {
  24792. this._currentCond.elseNode = new ShaderNode( method );
  24793. return this;
  24794. }
  24795. /**
  24796. * Represents a `switch` statement in TSL.
  24797. *
  24798. * @param {any} expression - Represents the expression.
  24799. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  24800. * @return {StackNode} A reference to this stack node.
  24801. */
  24802. Switch( expression ) {
  24803. this._expressionNode = nodeObject( expression );
  24804. return this;
  24805. }
  24806. /**
  24807. * Represents a `case` statement in TSL. The TSL version accepts an arbitrary numbers of values.
  24808. * The last parameter must be the callback method that should be executed in the `true` case.
  24809. *
  24810. * @param {...any} params - The values of the `Case()` statement as well as the callback method.
  24811. * @return {StackNode} A reference to this stack node.
  24812. */
  24813. Case( ...params ) {
  24814. const caseNodes = [];
  24815. // extract case nodes from the parameter list
  24816. if ( params.length >= 2 ) {
  24817. for ( let i = 0; i < params.length - 1; i ++ ) {
  24818. caseNodes.push( this._expressionNode.equal( nodeObject( params[ i ] ) ) );
  24819. }
  24820. } else {
  24821. error( 'TSL: Invalid parameter length. Case() requires at least two parameters.', new StackTrace() );
  24822. }
  24823. // extract method
  24824. const method = params[ params.length - 1 ];
  24825. const methodNode = new ShaderNode( method );
  24826. // chain multiple cases when using Case( 1, 2, 3, () => {} )
  24827. let caseNode = caseNodes[ 0 ];
  24828. for ( let i = 1; i < caseNodes.length; i ++ ) {
  24829. caseNode = caseNode.or( caseNodes[ i ] );
  24830. }
  24831. // build condition
  24832. const condNode = select( caseNode, methodNode );
  24833. if ( this._currentCond === null ) {
  24834. this._currentCond = condNode;
  24835. return this.addToStack( this._currentCond );
  24836. } else {
  24837. this._currentCond.elseNode = condNode;
  24838. this._currentCond = condNode;
  24839. return this;
  24840. }
  24841. }
  24842. /**
  24843. * Represents the default code block of a Switch/Case statement.
  24844. *
  24845. * @param {Function} method - TSL code which is executed in the `else` case.
  24846. * @return {StackNode} A reference to this stack node.
  24847. */
  24848. Default( method ) {
  24849. this.Else( method );
  24850. return this;
  24851. }
  24852. setup( builder ) {
  24853. const nodeProperties = builder.getNodeProperties( this );
  24854. let index = 0;
  24855. for ( const childNode of this.getChildren() ) {
  24856. if ( childNode.isVarNode && childNode.isIntent( builder ) ) {
  24857. if ( childNode.isAssign( builder ) !== true ) {
  24858. continue;
  24859. }
  24860. }
  24861. nodeProperties[ 'node' + index ++ ] = childNode;
  24862. }
  24863. // return a outputNode if exists or null
  24864. return nodeProperties.outputNode || null;
  24865. }
  24866. build( builder, ...params ) {
  24867. const previousStack = getCurrentStack();
  24868. const buildStage = builder.buildStage;
  24869. setCurrentStack( this );
  24870. builder.setActiveStack( this );
  24871. //
  24872. for ( let i = 0; i < this.nodes.length; i ++ ) {
  24873. const node = this.nodes[ i ];
  24874. const previousNode = this._currentNode;
  24875. this._currentNode = node;
  24876. if ( node.isVarNode && node.isIntent( builder ) ) {
  24877. if ( node.isAssign( builder ) !== true ) {
  24878. continue;
  24879. }
  24880. }
  24881. if ( buildStage === 'setup' ) {
  24882. node.build( builder );
  24883. } else if ( buildStage === 'analyze' ) {
  24884. node.build( builder, this );
  24885. } else if ( buildStage === 'generate' ) {
  24886. const stages = builder.getDataFromNode( node, 'any' ).stages;
  24887. const parents = stages && stages[ builder.shaderStage ];
  24888. if ( node.isVarNode && parents && parents.length === 1 && parents[ 0 ] && parents[ 0 ].isStackNode ) {
  24889. continue; // skip var nodes that are only used in .toVarying()
  24890. }
  24891. node.build( builder, 'void' );
  24892. }
  24893. this._currentNode = previousNode;
  24894. }
  24895. //
  24896. let result;
  24897. if ( this.outputNode ) {
  24898. const buildResult = this.outputNode.build( builder, ...params );
  24899. if ( builder.buildStage !== 'generate' || this.outputNode.getNodeType( builder ) !== 'void' ) {
  24900. result = buildResult;
  24901. }
  24902. } else {
  24903. result = super.build( builder, ...params );
  24904. }
  24905. setCurrentStack( previousStack );
  24906. builder.removeActiveStack( this );
  24907. return result;
  24908. }
  24909. }
  24910. /**
  24911. * TSL function for creating a stack node.
  24912. *
  24913. * @tsl
  24914. * @function
  24915. * @param {?StackNode} [parent=null] - The parent stack node.
  24916. * @returns {StackNode}
  24917. */
  24918. const stack = /*@__PURE__*/ nodeProxy( StackNode ).setParameterLength( 0, 1 );
  24919. /**
  24920. * Generates a layout for struct members.
  24921. * This function takes an object representing struct members and returns an array of member layouts.
  24922. * Each member layout includes the member's name, type, and whether it is atomic.
  24923. *
  24924. * @param {Object.<string, string|Object>} members - An object where keys are member names and values are either types (as strings) or objects with type and atomic properties.
  24925. * @returns {Array.<{name: string, type: string, atomic: boolean}>} An array of member layouts.
  24926. */
  24927. function getMembersLayout( members ) {
  24928. return Object.entries( members ).map( ( [ name, value ] ) => {
  24929. if ( typeof value === 'string' ) {
  24930. return { name, type: value, atomic: false };
  24931. }
  24932. return { name, type: value.type, atomic: value.atomic || false };
  24933. } );
  24934. }
  24935. /**
  24936. * Represents a struct type node in the node-based system.
  24937. * This class is used to define and manage the layout and types of struct members.
  24938. * It extends the base Node class and provides methods to get the length of the struct,
  24939. * retrieve member types, and generate the struct type for a builder.
  24940. *
  24941. * @augments Node
  24942. */
  24943. class StructTypeNode extends Node {
  24944. static get type() {
  24945. return 'StructTypeNode';
  24946. }
  24947. /**
  24948. * Creates an instance of StructTypeNode.
  24949. *
  24950. * @param {Object} membersLayout - The layout of the members for the struct.
  24951. * @param {?string} [name=null] - The optional name of the struct.
  24952. */
  24953. constructor( membersLayout, name = null ) {
  24954. super( 'struct' );
  24955. /**
  24956. * The layout of the members for the struct
  24957. *
  24958. * @type {Array.<{name: string, type: string, atomic: boolean}>}
  24959. */
  24960. this.membersLayout = getMembersLayout( membersLayout );
  24961. /**
  24962. * The name of the struct.
  24963. *
  24964. * @type {?string}
  24965. * @default null
  24966. */
  24967. this.name = name;
  24968. /**
  24969. * This flag can be used for type testing.
  24970. *
  24971. * @type {boolean}
  24972. * @readonly
  24973. * @default true
  24974. */
  24975. this.isStructTypeNode = true;
  24976. }
  24977. /**
  24978. * Returns the length of the struct in 4-byte elements (e.g. float or int components).
  24979. * The length is calculated by summing the lengths of the struct's members, accounting for memory alignment.
  24980. * To get the size in bytes, multiply the returned value by 4.
  24981. *
  24982. * @returns {number} The length of the struct in 4-byte elements.
  24983. */
  24984. getLength() {
  24985. let maxAlignment = 1; // maximum alignment value in this struct
  24986. let offset = 0; // global buffer offset in 4 byte elements
  24987. for ( const member of this.membersLayout ) {
  24988. const type = member.type;
  24989. const itemSize = getMemoryLengthFromType( type );
  24990. const alignment = getAlignmentFromType( type );
  24991. maxAlignment = Math.max( maxAlignment, alignment );
  24992. const chunkOffset = offset % maxAlignment; // offset in the current chunk of maxAlignment elements
  24993. const overhang = chunkOffset % alignment; // distance from the last aligned offset
  24994. if ( overhang !== 0 ) {
  24995. offset += alignment - overhang; // move to next aligned offset
  24996. }
  24997. offset += itemSize;
  24998. }
  24999. return ( Math.ceil( offset / maxAlignment ) * maxAlignment ); // ensure length is a multiple of maxAlignment
  25000. }
  25001. getMemberType( builder, name ) {
  25002. const member = this.membersLayout.find( m => m.name === name );
  25003. return member ? member.type : 'void';
  25004. }
  25005. generateNodeType( builder ) {
  25006. const structType = builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  25007. return structType.name;
  25008. }
  25009. setup( builder ) {
  25010. builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  25011. builder.addInclude( this );
  25012. }
  25013. generate( builder ) {
  25014. return this.getNodeType( builder );
  25015. }
  25016. }
  25017. /**
  25018. * StructNode allows to create custom structures with multiple members.
  25019. * This can also be used to define structures in attribute and uniform data.
  25020. *
  25021. * ```js
  25022. * // Define a custom struct
  25023. * const BoundingBox = struct( { min: 'vec3', max: 'vec3' } );
  25024. *
  25025. * // Create a new instance of the struct
  25026. * const bb = BoundingBox( vec3( 0 ), vec3( 1 ) ); // style 1
  25027. * const bb = BoundingBox( { min: vec3( 0 ), max: vec3( 1 ) } ); // style 2
  25028. *
  25029. * // Access the struct members
  25030. * const min = bb.get( 'min' );
  25031. *
  25032. * // Assign a new value to a member
  25033. * min.assign( vec3() );
  25034. * ```
  25035. * @augments Node
  25036. */
  25037. class StructNode extends Node {
  25038. static get type() {
  25039. return 'StructNode';
  25040. }
  25041. constructor( structTypeNode, values ) {
  25042. super( 'vec3' );
  25043. this.structTypeNode = structTypeNode;
  25044. this.values = values;
  25045. this.isStructNode = true;
  25046. }
  25047. generateNodeType( builder ) {
  25048. return this.structTypeNode.getNodeType( builder );
  25049. }
  25050. getMemberType( builder, name ) {
  25051. return this.structTypeNode.getMemberType( builder, name );
  25052. }
  25053. _getChildren() {
  25054. // Ensure struct type is the last child for correct code generation order
  25055. const children = super._getChildren();
  25056. const structTypeProperty = children.find( child => child.childNode === this.structTypeNode );
  25057. children.splice( children.indexOf( structTypeProperty ), 1 );
  25058. children.push( structTypeProperty );
  25059. return children;
  25060. }
  25061. generate( builder ) {
  25062. const nodeVar = builder.getVarFromNode( this );
  25063. const structType = nodeVar.type;
  25064. const propertyName = builder.getPropertyName( nodeVar );
  25065. builder.addLineFlowCode( `${ propertyName } = ${ builder.generateStruct( structType, this.structTypeNode.membersLayout, this.values ) }`, this );
  25066. return nodeVar.name;
  25067. }
  25068. }
  25069. /**
  25070. * TSL function for creating a struct node.
  25071. *
  25072. * @tsl
  25073. * @function
  25074. * @param {Object} membersLayout - The layout of the struct members.
  25075. * @param {?string} [name=null] - The name of the struct.
  25076. * @returns {Function} The struct function.
  25077. */
  25078. const struct = ( membersLayout, name = null ) => {
  25079. const structType = new StructTypeNode( membersLayout, name );
  25080. const struct = ( ...params ) => {
  25081. let values = null;
  25082. if ( params.length > 0 ) {
  25083. if ( params[ 0 ].isNode ) {
  25084. values = {};
  25085. const names = Object.keys( membersLayout );
  25086. for ( let i = 0; i < params.length; i ++ ) {
  25087. values[ names[ i ] ] = params[ i ];
  25088. }
  25089. } else {
  25090. values = params[ 0 ];
  25091. }
  25092. }
  25093. return new StructNode( structType, values );
  25094. };
  25095. return nodeProxyConstructor( struct, structType );
  25096. };
  25097. /**
  25098. * This node can be used to define multiple outputs in a shader programs.
  25099. *
  25100. * @augments Node
  25101. */
  25102. class OutputStructNode extends Node {
  25103. static get type() {
  25104. return 'OutputStructNode';
  25105. }
  25106. /**
  25107. * Constructs a new output struct node. The constructor can be invoked with an
  25108. * arbitrary number of nodes representing the members.
  25109. *
  25110. * @param {...Node} members - A parameter list of nodes.
  25111. */
  25112. constructor( ...members ) {
  25113. super();
  25114. /**
  25115. * An array of nodes which defines the output.
  25116. *
  25117. * @type {Array<Node>}
  25118. */
  25119. this.members = members;
  25120. /**
  25121. * This flag can be used for type testing.
  25122. *
  25123. * @type {boolean}
  25124. * @readonly
  25125. * @default true
  25126. */
  25127. this.isOutputStructNode = true;
  25128. }
  25129. generateNodeType( /*builder*/ ) {
  25130. return 'OutputType';
  25131. }
  25132. generate( builder ) {
  25133. const nodeData = builder.getDataFromNode( this );
  25134. if ( nodeData.membersLayout === undefined ) {
  25135. const members = this.members;
  25136. const membersLayout = [];
  25137. for ( let i = 0; i < members.length; i ++ ) {
  25138. const name = 'm' + i;
  25139. const type = members[ i ].getNodeType( builder );
  25140. membersLayout.push( { name, type, index: i } );
  25141. }
  25142. nodeData.membersLayout = membersLayout;
  25143. nodeData.structType = builder.getOutputStructTypeFromNode( this, nodeData.membersLayout );
  25144. }
  25145. //
  25146. const propertyName = builder.getOutputStructName();
  25147. const members = this.members;
  25148. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  25149. for ( let i = 0; i < members.length; i ++ ) {
  25150. const snippet = members[ i ].build( builder, nodeData.membersLayout[ i ].type );
  25151. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  25152. }
  25153. return propertyName;
  25154. }
  25155. }
  25156. /**
  25157. * TSL function for creating an output struct node.
  25158. *
  25159. * @tsl
  25160. * @function
  25161. * @param {...Node} members - A parameter list of nodes.
  25162. * @returns {OutputStructNode}
  25163. */
  25164. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  25165. /**
  25166. * Represents blending configuration.
  25167. *
  25168. * This class encapsulates all blending-related properties that control how
  25169. * a material's colors are combined with the colors already in the frame buffer.
  25170. */
  25171. class BlendMode {
  25172. /**
  25173. * Constructs a new blending configuration.
  25174. *
  25175. * @param {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending|MaterialBlending)} [blending=NormalBlending] - The blending mode.
  25176. */
  25177. constructor( blending = NormalBlending ) {
  25178. /**
  25179. * Defines the blending type.
  25180. *
  25181. * It must be set to `CustomBlending` if custom blending properties like
  25182. * {@link BlendMode#blendSrc}, {@link BlendMode#blendDst} or {@link BlendMode#blendEquation}
  25183. * should have any effect.
  25184. *
  25185. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending|MaterialBlending)}
  25186. * @default NormalBlending
  25187. */
  25188. this.blending = blending;
  25189. /**
  25190. * Defines the blending source factor.
  25191. *
  25192. * This determines how the source (incoming) fragment color is factored before being added
  25193. * to the destination (existing) fragment color in the frame buffer.
  25194. *
  25195. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  25196. * @default SrcAlphaFactor
  25197. */
  25198. this.blendSrc = SrcAlphaFactor;
  25199. /**
  25200. * Defines the blending destination factor.
  25201. *
  25202. * This determines how the destination (existing) fragment color in the frame buffer
  25203. * is factored before being combined with the source (incoming) fragment color.
  25204. *
  25205. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  25206. * @default OneMinusSrcAlphaFactor
  25207. */
  25208. this.blendDst = OneMinusSrcAlphaFactor;
  25209. /**
  25210. * Defines the blending equation.
  25211. *
  25212. * This determines how the source and destination colors are combined.
  25213. *
  25214. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  25215. * @default AddEquation
  25216. */
  25217. this.blendEquation = AddEquation;
  25218. /**
  25219. * Defines the blending source alpha factor.
  25220. *
  25221. * When set, this allows separate control of the alpha channel's source blending factor.
  25222. * If `null`, {@link BlendMode#blendSrc} is used for the alpha channel as well.
  25223. *
  25224. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  25225. * @default null
  25226. */
  25227. this.blendSrcAlpha = null;
  25228. /**
  25229. * Defines the blending destination alpha factor.
  25230. *
  25231. * When set, this allows separate control of the alpha channel's destination blending factor.
  25232. * If `null`, {@link BlendMode#blendDst} is used for the alpha channel as well.
  25233. *
  25234. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  25235. * @default null
  25236. */
  25237. this.blendDstAlpha = null;
  25238. /**
  25239. * Defines the blending equation of the alpha channel.
  25240. *
  25241. * When set, this allows separate control of the alpha channel's blending equation.
  25242. * If `null`, {@link BlendMode#blendEquation} is used for the alpha channel as well.
  25243. *
  25244. * @type {?(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  25245. * @default null
  25246. */
  25247. this.blendEquationAlpha = null;
  25248. /**
  25249. * Defines whether to premultiply the alpha (transparency) value.
  25250. *
  25251. * If `true`, the RGB color of the texture or material is multiplied by its alpha value.
  25252. * This is useful for transparent textures/materials where the color data
  25253. * should already include the transparency information.
  25254. *
  25255. * @type {boolean}
  25256. * @default false
  25257. */
  25258. this.premultiplyAlpha = false;
  25259. }
  25260. /**
  25261. * Copies the blending properties from the given source to this instance.
  25262. *
  25263. * @param {BlendMode} source - The blending configuration to copy from.
  25264. * @return {BlendMode} A reference to this instance.
  25265. */
  25266. copy( source ) {
  25267. this.blending = source.blending;
  25268. this.blendSrc = source.blendSrc;
  25269. this.blendDst = source.blendDst;
  25270. this.blendEquation = source.blendEquation;
  25271. this.blendSrcAlpha = source.blendSrcAlpha;
  25272. this.blendDstAlpha = source.blendDstAlpha;
  25273. this.blendEquationAlpha = source.blendEquationAlpha;
  25274. this.premultiplyAlpha = source.premultiplyAlpha;
  25275. return this;
  25276. }
  25277. /**
  25278. * Returns a clone of this blending configuration.
  25279. *
  25280. * @return {BlendMode} A new Blending instance with the same properties.
  25281. */
  25282. clone() {
  25283. return new this.constructor().copy( this );
  25284. }
  25285. }
  25286. // Predefined blend modes for MRT nodes.
  25287. const _noBlending = /**@__PURE__*/ new BlendMode( NoBlending );
  25288. const _materialBlending = /**@__PURE__*/ new BlendMode( MaterialBlending );
  25289. /**
  25290. * Returns the MRT texture index for the given name.
  25291. *
  25292. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  25293. * @param {string} name - The name of the MRT texture which index is requested.
  25294. * @return {number} The texture index.
  25295. */
  25296. function getTextureIndex( textures, name ) {
  25297. for ( let i = 0; i < textures.length; i ++ ) {
  25298. if ( textures[ i ].name === name ) {
  25299. return i;
  25300. }
  25301. }
  25302. return -1;
  25303. }
  25304. /**
  25305. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  25306. * post-processing is shown below:
  25307. * ```js
  25308. * const mrtNode = mrt( {
  25309. * output: output,
  25310. * normal: normalView
  25311. * } ) ;
  25312. * ```
  25313. * The MRT output is defined as a dictionary.
  25314. *
  25315. * @augments OutputStructNode
  25316. */
  25317. class MRTNode extends OutputStructNode {
  25318. static get type() {
  25319. return 'MRTNode';
  25320. }
  25321. /**
  25322. * Constructs a new output struct node.
  25323. *
  25324. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  25325. */
  25326. constructor( outputNodes ) {
  25327. super();
  25328. /**
  25329. * A dictionary representing the MRT outputs. The key
  25330. * is the name of the output, the value the node which produces
  25331. * the output result.
  25332. *
  25333. * @type {Object<string, Node>}
  25334. */
  25335. this.outputNodes = outputNodes;
  25336. /**
  25337. * A dictionary storing the blend modes for each output.
  25338. *
  25339. * @type {Object<string, BlendMode>}
  25340. */
  25341. this.blendModes = {
  25342. output: _materialBlending
  25343. };
  25344. /**
  25345. * This flag can be used for type testing.
  25346. *
  25347. * @type {boolean}
  25348. * @readonly
  25349. * @default true
  25350. */
  25351. this.isMRTNode = true;
  25352. }
  25353. /**
  25354. * Sets the blend mode for the given output name.
  25355. *
  25356. * @param {string} name - The name of the output.
  25357. * @param {BlendMode} blend - The blending mode.
  25358. * @return {MRTNode} The current MRT node.
  25359. */
  25360. setBlendMode( name, blend ) {
  25361. this.blendModes[ name ] = blend;
  25362. return this;
  25363. }
  25364. /**
  25365. * Returns the blend mode for the given output name.
  25366. *
  25367. * @param {string} name - The name of the output.
  25368. * @return {BlendMode} The blend mode.
  25369. */
  25370. getBlendMode( name ) {
  25371. return this.blendModes[ name ] || _noBlending;
  25372. }
  25373. /**
  25374. * Returns `true` if the MRT node has an output with the given name.
  25375. *
  25376. * @param {string} name - The name of the output.
  25377. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  25378. */
  25379. has( name ) {
  25380. return this.outputNodes[ name ] !== undefined;
  25381. }
  25382. /**
  25383. * Returns the output node for the given name.
  25384. *
  25385. * @param {string} name - The name of the output.
  25386. * @return {Node} The output node.
  25387. */
  25388. get( name ) {
  25389. return this.outputNodes[ name ];
  25390. }
  25391. /**
  25392. * Merges the outputs of the given MRT node with the outputs of this node.
  25393. *
  25394. * @param {MRTNode} mrtNode - The MRT to merge.
  25395. * @return {MRTNode} A new MRT node with merged outputs..
  25396. */
  25397. merge( mrtNode ) {
  25398. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  25399. const blendings = { ...this.blendModes, ...mrtNode.blendModes };
  25400. const mrtTarget = mrt( outputs );
  25401. mrtTarget.blendings = blendings;
  25402. return mrtTarget;
  25403. }
  25404. setup( builder ) {
  25405. const outputNodes = this.outputNodes;
  25406. const mrt = builder.renderer.getRenderTarget();
  25407. const members = [];
  25408. const textures = mrt.textures;
  25409. for ( const name in outputNodes ) {
  25410. const index = getTextureIndex( textures, name );
  25411. // Ignore if the output exists in the MRT but has never been used.
  25412. if ( index === -1 ) continue;
  25413. const type = builder.getOutputType( index );
  25414. members[ index ] = outputNodes[ name ].convert( type );
  25415. }
  25416. this.members = members;
  25417. return super.setup( builder );
  25418. }
  25419. }
  25420. /**
  25421. * TSL function for creating a MRT node.
  25422. *
  25423. * @tsl
  25424. * @function
  25425. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  25426. * @returns {MRTNode}
  25427. */
  25428. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  25429. /**
  25430. * This node represents an operation that reinterprets the bit representation of a value
  25431. * in one type as a value in another type.
  25432. *
  25433. * @augments TempNode
  25434. */
  25435. class BitcastNode extends TempNode {
  25436. static get type() {
  25437. return 'BitcastNode';
  25438. }
  25439. /**
  25440. * Constructs a new bitcast node.
  25441. *
  25442. * @param {Node} valueNode - The value to convert.
  25443. * @param {string} conversionType - The type to convert to.
  25444. * @param {?string} [inputType = null] - The expected input data type of the bitcast operation.
  25445. */
  25446. constructor( valueNode, conversionType, inputType = null ) {
  25447. super();
  25448. /**
  25449. * The data to bitcast to a new type.
  25450. *
  25451. * @type {Node}
  25452. */
  25453. this.valueNode = valueNode;
  25454. /**
  25455. * The type the value will be converted to.
  25456. *
  25457. * @type {string}
  25458. */
  25459. this.conversionType = conversionType;
  25460. /**
  25461. * The expected input data type of the bitcast operation.
  25462. *
  25463. *
  25464. * @type {string}
  25465. * @default null
  25466. */
  25467. this.inputType = inputType;
  25468. /**
  25469. * This flag can be used for type testing.
  25470. *
  25471. * @type {boolean}
  25472. * @readonly
  25473. * @default true
  25474. */
  25475. this.isBitcastNode = true;
  25476. }
  25477. generateNodeType( builder ) {
  25478. // GLSL aliasing
  25479. if ( this.inputType !== null ) {
  25480. const valueType = this.valueNode.getNodeType( builder );
  25481. const valueLength = builder.getTypeLength( valueType );
  25482. return builder.getTypeFromLength( valueLength, this.conversionType );
  25483. }
  25484. return this.conversionType;
  25485. }
  25486. generate( builder ) {
  25487. const type = this.getNodeType( builder );
  25488. let inputType = '';
  25489. if ( this.inputType !== null ) {
  25490. const valueType = this.valueNode.getNodeType( builder );
  25491. const valueTypeLength = builder.getTypeLength( valueType );
  25492. inputType = valueTypeLength === 1 ? this.inputType : builder.changeComponentType( valueType, this.inputType );
  25493. } else {
  25494. inputType = this.valueNode.getNodeType( builder );
  25495. }
  25496. return `${ builder.getBitcastMethod( type, inputType ) }( ${ this.valueNode.build( builder, inputType ) } )`;
  25497. }
  25498. }
  25499. /**
  25500. * Reinterpret the bit representation of a value in one type as a value in another type.
  25501. *
  25502. * @tsl
  25503. * @function
  25504. * @param {Node | number} x - The parameter.
  25505. * @param {string} y - The new type.
  25506. * @returns {Node}
  25507. */
  25508. const bitcast = /*@__PURE__*/ nodeProxyIntent( BitcastNode ).setParameterLength( 2 );
  25509. /**
  25510. * Bitcasts a float or a vector of floats to a corresponding integer type with the same element size.
  25511. *
  25512. * @tsl
  25513. * @function
  25514. * @param {Node<float>} value - The float or vector of floats to bitcast.
  25515. * @returns {BitcastNode}
  25516. */
  25517. const floatBitsToInt = ( value ) => new BitcastNode( value, 'int', 'float' );
  25518. /**
  25519. * Bitcasts a float or a vector of floats to a corresponding unsigned integer type with the same element size.
  25520. *
  25521. * @tsl
  25522. * @function
  25523. * @param {Node<float>} value - The float or vector of floats to bitcast.
  25524. * @returns {BitcastNode}
  25525. */
  25526. const floatBitsToUint = ( value ) => new BitcastNode( value, 'uint', 'float' );
  25527. /**
  25528. * Bitcasts an integer or a vector of integers to a corresponding float type with the same element size.
  25529. *
  25530. * @tsl
  25531. * @function
  25532. * @param {Node<int>} value - The integer or vector of integers to bitcast.
  25533. * @returns {BitcastNode}
  25534. */
  25535. const intBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'int' );
  25536. /**
  25537. * Bitcast an unsigned integer or a vector of unsigned integers to a corresponding float type with the same element size.
  25538. *
  25539. * @tsl
  25540. * @function
  25541. * @param {Node<uint>} value - The unsigned integer or vector of unsigned integers to bitcast.
  25542. * @returns {BitcastNode}
  25543. */
  25544. const uintBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'uint' );
  25545. const registeredBitcountFunctions = {};
  25546. /**
  25547. * This node represents an operation that counts the bits of a piece of shader data.
  25548. *
  25549. * @augments MathNode
  25550. */
  25551. class BitcountNode extends MathNode {
  25552. static get type() {
  25553. return 'BitcountNode';
  25554. }
  25555. /**
  25556. * Constructs a new math node.
  25557. *
  25558. * @param {'countTrailingZeros'|'countLeadingZeros'|'countOneBits'} method - The method name.
  25559. * @param {Node} aNode - The first input.
  25560. */
  25561. constructor( method, aNode ) {
  25562. super( method, aNode );
  25563. /**
  25564. * This flag can be used for type testing.
  25565. *
  25566. * @type {boolean}
  25567. * @readonly
  25568. * @default true
  25569. */
  25570. this.isBitcountNode = true;
  25571. }
  25572. /**
  25573. * Casts the input value of the function to an integer if necessary.
  25574. *
  25575. * @private
  25576. * @param {Node<uint>|Node<int>} inputNode - The input value.
  25577. * @param {Node<uint>} outputNode - The output value.
  25578. * @param {string} elementType - The type of the input value.
  25579. */
  25580. _resolveElementType( inputNode, outputNode, elementType ) {
  25581. if ( elementType === 'int' ) {
  25582. outputNode.assign( bitcast( inputNode, 'uint' ) );
  25583. } else {
  25584. outputNode.assign( inputNode );
  25585. }
  25586. }
  25587. _returnDataNode( inputType ) {
  25588. switch ( inputType ) {
  25589. case 'uint': {
  25590. return uint;
  25591. }
  25592. case 'int': {
  25593. return int;
  25594. }
  25595. case 'uvec2': {
  25596. return uvec2;
  25597. }
  25598. case 'uvec3': {
  25599. return uvec3;
  25600. }
  25601. case 'uvec4': {
  25602. return uvec4;
  25603. }
  25604. case 'ivec2': {
  25605. return ivec2;
  25606. }
  25607. case 'ivec3': {
  25608. return ivec3;
  25609. }
  25610. case 'ivec4': {
  25611. return ivec4;
  25612. }
  25613. }
  25614. }
  25615. /**
  25616. * Creates and registers a reusable GLSL function that emulates the behavior of countTrailingZeros.
  25617. *
  25618. * @private
  25619. * @param {string} method - The name of the function to create.
  25620. * @param {string} elementType - The type of the input value.
  25621. * @returns {Function} - The generated function
  25622. */
  25623. _createTrailingZerosBaseLayout( method, elementType ) {
  25624. const outputConvertNode = this._returnDataNode( elementType );
  25625. const fnDef = Fn( ( [ value ] ) => {
  25626. const v = uint( 0.0 );
  25627. this._resolveElementType( value, v, elementType );
  25628. const f = float( v.bitAnd( negate( v ) ) );
  25629. const uintBits = floatBitsToUint( f );
  25630. const numTrailingZeros = ( uintBits.shiftRight( 23 ) ).sub( 127 );
  25631. return outputConvertNode( numTrailingZeros );
  25632. } ).setLayout( {
  25633. name: method,
  25634. type: elementType,
  25635. inputs: [
  25636. { name: 'value', type: elementType }
  25637. ]
  25638. } );
  25639. return fnDef;
  25640. }
  25641. /**
  25642. * Creates and registers a reusable GLSL function that emulates the behavior of countLeadingZeros.
  25643. *
  25644. * @private
  25645. * @param {string} method - The name of the function to create.
  25646. * @param {string} elementType - The type of the input value.
  25647. * @returns {Function} - The generated function
  25648. */
  25649. _createLeadingZerosBaseLayout( method, elementType ) {
  25650. const outputConvertNode = this._returnDataNode( elementType );
  25651. const fnDef = Fn( ( [ value ] ) => {
  25652. If( value.equal( uint( 0 ) ), () => {
  25653. return uint( 32 );
  25654. } );
  25655. const v = uint( 0 );
  25656. const n = uint( 0 );
  25657. this._resolveElementType( value, v, elementType );
  25658. If( v.shiftRight( 16 ).equal( 0 ), () => {
  25659. n.addAssign( 16 );
  25660. v.shiftLeftAssign( 16 );
  25661. } );
  25662. If( v.shiftRight( 24 ).equal( 0 ), () => {
  25663. n.addAssign( 8 );
  25664. v.shiftLeftAssign( 8 );
  25665. } );
  25666. If( v.shiftRight( 28 ).equal( 0 ), () => {
  25667. n.addAssign( 4 );
  25668. v.shiftLeftAssign( 4 );
  25669. } );
  25670. If( v.shiftRight( 30 ).equal( 0 ), () => {
  25671. n.addAssign( 2 );
  25672. v.shiftLeftAssign( 2 );
  25673. } );
  25674. If( v.shiftRight( 31 ).equal( 0 ), () => {
  25675. n.addAssign( 1 );
  25676. } );
  25677. return outputConvertNode( n );
  25678. } ).setLayout( {
  25679. name: method,
  25680. type: elementType,
  25681. inputs: [
  25682. { name: 'value', type: elementType }
  25683. ]
  25684. } );
  25685. return fnDef;
  25686. }
  25687. /**
  25688. * Creates and registers a reusable GLSL function that emulates the behavior of countOneBits.
  25689. *
  25690. * @private
  25691. * @param {string} method - The name of the function to create.
  25692. * @param {string} elementType - The type of the input value.
  25693. * @returns {Function} - The generated function
  25694. */
  25695. _createOneBitsBaseLayout( method, elementType ) {
  25696. const outputConvertNode = this._returnDataNode( elementType );
  25697. const fnDef = Fn( ( [ value ] ) => {
  25698. const v = uint( 0.0 );
  25699. this._resolveElementType( value, v, elementType );
  25700. v.assign( v.sub( v.shiftRight( uint( 1 ) ).bitAnd( uint( 0x55555555 ) ) ) );
  25701. v.assign( v.bitAnd( uint( 0x33333333 ) ).add( v.shiftRight( uint( 2 ) ).bitAnd( uint( 0x33333333 ) ) ) );
  25702. const numBits = v.add( v.shiftRight( uint( 4 ) ) ).bitAnd( uint( 0xF0F0F0F ) ).mul( uint( 0x1010101 ) ).shiftRight( uint( 24 ) );
  25703. return outputConvertNode( numBits );
  25704. } ).setLayout( {
  25705. name: method,
  25706. type: elementType,
  25707. inputs: [
  25708. { name: 'value', type: elementType }
  25709. ]
  25710. } );
  25711. return fnDef;
  25712. }
  25713. /**
  25714. * Creates and registers a reusable GLSL function that emulates the behavior of the specified bitcount function.
  25715. * including considerations for component-wise bitcounts on vector type inputs.
  25716. *
  25717. * @private
  25718. * @param {string} method - The name of the function to create.
  25719. * @param {string} inputType - The type of the input value.
  25720. * @param {number} typeLength - The vec length of the input value.
  25721. * @param {Function} baseFn - The base function that operates on an individual component of the vector.
  25722. * @returns {Function} - The alias function for the specified bitcount method.
  25723. */
  25724. _createMainLayout( method, inputType, typeLength, baseFn ) {
  25725. const outputConvertNode = this._returnDataNode( inputType );
  25726. const fnDef = Fn( ( [ value ] ) => {
  25727. if ( typeLength === 1 ) {
  25728. return outputConvertNode( baseFn( value ) );
  25729. } else {
  25730. const vec = outputConvertNode( 0 );
  25731. const components = [ 'x', 'y', 'z', 'w' ];
  25732. for ( let i = 0; i < typeLength; i ++ ) {
  25733. const component = components[ i ];
  25734. vec[ component ].assign( baseFn( value[ component ] ) );
  25735. }
  25736. return vec;
  25737. }
  25738. } ).setLayout( {
  25739. name: method,
  25740. type: inputType,
  25741. inputs: [
  25742. { name: 'value', type: inputType }
  25743. ]
  25744. } );
  25745. return fnDef;
  25746. }
  25747. setup( builder ) {
  25748. const { method, aNode } = this;
  25749. const { renderer } = builder;
  25750. if ( renderer.backend.isWebGPUBackend ) {
  25751. // use built-in WGSL functions for WebGPU
  25752. return super.setup( builder );
  25753. }
  25754. const inputType = this.getInputType( builder );
  25755. const elementType = builder.getElementType( inputType );
  25756. const typeLength = builder.getTypeLength( inputType );
  25757. const baseMethod = `${method}_base_${elementType}`;
  25758. const newMethod = `${method}_${inputType}`;
  25759. let baseFn = registeredBitcountFunctions[ baseMethod ];
  25760. if ( baseFn === undefined ) {
  25761. switch ( method ) {
  25762. case BitcountNode.COUNT_LEADING_ZEROS: {
  25763. baseFn = this._createLeadingZerosBaseLayout( baseMethod, elementType );
  25764. break;
  25765. }
  25766. case BitcountNode.COUNT_TRAILING_ZEROS: {
  25767. baseFn = this._createTrailingZerosBaseLayout( baseMethod, elementType );
  25768. break;
  25769. }
  25770. case BitcountNode.COUNT_ONE_BITS: {
  25771. baseFn = this._createOneBitsBaseLayout( baseMethod, elementType );
  25772. break;
  25773. }
  25774. }
  25775. registeredBitcountFunctions[ baseMethod ] = baseFn;
  25776. }
  25777. let fn = registeredBitcountFunctions[ newMethod ];
  25778. if ( fn === undefined ) {
  25779. fn = this._createMainLayout( newMethod, inputType, typeLength, baseFn );
  25780. registeredBitcountFunctions[ newMethod ] = fn;
  25781. }
  25782. const output = Fn( () => {
  25783. return fn(
  25784. aNode,
  25785. );
  25786. } );
  25787. return output();
  25788. }
  25789. }
  25790. BitcountNode.COUNT_TRAILING_ZEROS = 'countTrailingZeros';
  25791. BitcountNode.COUNT_LEADING_ZEROS = 'countLeadingZeros';
  25792. BitcountNode.COUNT_ONE_BITS = 'countOneBits';
  25793. /**
  25794. * Finds the number of consecutive 0 bits from the least significant bit of the input value,
  25795. * which is also the index of the least significant bit of the input value.
  25796. *
  25797. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  25798. *
  25799. * @tsl
  25800. * @function
  25801. * @param {Node | number} x - The input value.
  25802. * @returns {Node}
  25803. */
  25804. const countTrailingZeros = /*@__PURE__*/ nodeProxyIntent( BitcountNode, BitcountNode.COUNT_TRAILING_ZEROS ).setParameterLength( 1 );
  25805. /**
  25806. * Finds the number of consecutive 0 bits starting from the most significant bit of the input value.
  25807. *
  25808. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  25809. *
  25810. * @tsl
  25811. * @function
  25812. * @param {Node | number} x - The input value.
  25813. * @returns {Node}
  25814. */
  25815. const countLeadingZeros = /*@__PURE__*/ nodeProxyIntent( BitcountNode, BitcountNode.COUNT_LEADING_ZEROS ).setParameterLength( 1 );
  25816. /**
  25817. * Finds the number of '1' bits set in the input value
  25818. *
  25819. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  25820. *
  25821. * @tsl
  25822. * @function
  25823. * @returns {Node}
  25824. */
  25825. const countOneBits = /*@__PURE__*/ nodeProxyIntent( BitcountNode, BitcountNode.COUNT_ONE_BITS ).setParameterLength( 1 );
  25826. /**
  25827. * Generates a hash value in the range `[0, 1]` from the given seed.
  25828. *
  25829. * @tsl
  25830. * @function
  25831. * @param {Node<float>} seed - The seed.
  25832. * @return {Node<float>} The hash value.
  25833. */
  25834. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  25835. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  25836. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  25837. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  25838. const result = word.shiftRight( 22 ).bitXor( word );
  25839. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  25840. } );
  25841. /**
  25842. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  25843. * The corners are mapped to `0` and the center to `1`.
  25844. * Reference: {@link https://iquilezles.org/articles/functions/}.
  25845. *
  25846. * @tsl
  25847. * @function
  25848. * @param {Node<float>} x - The value to remap.
  25849. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  25850. * @return {Node<float>} The remapped value.
  25851. */
  25852. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  25853. /**
  25854. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  25855. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  25856. * Reference: {@link https://iquilezles.org/articles/functions/}.
  25857. *
  25858. * @tsl
  25859. * @function
  25860. * @param {Node<float>} x - The value to remap.
  25861. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  25862. * @return {Node<float>} The remapped value.
  25863. */
  25864. 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 ) );
  25865. /**
  25866. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  25867. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  25868. * Reference: {@link https://iquilezles.org/articles/functions/}.
  25869. *
  25870. * @tsl
  25871. * @function
  25872. * @param {Node<float>} x - The value to remap.
  25873. * @param {Node<float>} a - First control parameter.
  25874. * @param {Node<float>} b - Second control parameter.
  25875. * @return {Node<float>} The remapped value.
  25876. */
  25877. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  25878. /**
  25879. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  25880. * Reference: {@link https://iquilezles.org/articles/functions/}.
  25881. *
  25882. * @tsl
  25883. * @function
  25884. * @param {Node<float>} x - The value to compute the sin for.
  25885. * @param {Node<float>} k - Controls the amount of bounces.
  25886. * @return {Node<float>} The result value.
  25887. */
  25888. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  25889. /**
  25890. * This node represents an operation that packs floating-point values of a vector into an unsigned 32-bit integer
  25891. *
  25892. * @augments TempNode
  25893. */
  25894. class PackFloatNode extends TempNode {
  25895. static get type() {
  25896. return 'PackFloatNode';
  25897. }
  25898. /**
  25899. *
  25900. * @param {'snorm' | 'unorm' | 'float16'} encoding - The numeric encoding that describes how the float values are mapped to the integer range.
  25901. * @param {Node} vectorNode - The vector node to be packed
  25902. */
  25903. constructor( encoding, vectorNode ) {
  25904. super();
  25905. /**
  25906. * The vector to be packed.
  25907. *
  25908. * @type {Node}
  25909. */
  25910. this.vectorNode = vectorNode;
  25911. /**
  25912. * The numeric encoding.
  25913. *
  25914. * @type {string}
  25915. */
  25916. this.encoding = encoding;
  25917. /**
  25918. * This flag can be used for type testing.
  25919. *
  25920. * @type {boolean}
  25921. * @readonly
  25922. * @default true
  25923. */
  25924. this.isPackFloatNode = true;
  25925. }
  25926. generateNodeType() {
  25927. return 'uint';
  25928. }
  25929. generate( builder ) {
  25930. const inputType = this.vectorNode.getNodeType( builder );
  25931. return `${ builder.getFloatPackingMethod( this.encoding ) }(${ this.vectorNode.build( builder, inputType )})`;
  25932. }
  25933. }
  25934. /**
  25935. * Converts each component of the normalized float to 16-bit integer values. The results are packed into a single unsigned integer.
  25936. * round(clamp(c, -1, +1) * 32767.0)
  25937. *
  25938. * @tsl
  25939. * @function
  25940. * @param {Node<vec2>} value - The 2-component vector to be packed
  25941. * @returns {Node}
  25942. */
  25943. const packSnorm2x16 = /*@__PURE__*/ nodeProxyIntent( PackFloatNode, 'snorm' ).setParameterLength( 1 );
  25944. /**
  25945. * Converts each component of the normalized float to 16-bit integer values. The results are packed into a single unsigned integer.
  25946. * round(clamp(c, 0, +1) * 65535.0)
  25947. *
  25948. * @tsl
  25949. * @function
  25950. * @param {Node<vec2>} value - The 2-component vector to be packed
  25951. * @returns {Node}
  25952. */
  25953. const packUnorm2x16 = /*@__PURE__*/ nodeProxyIntent( PackFloatNode, 'unorm' ).setParameterLength( 1 );
  25954. /**
  25955. * Converts each component of the vec2 to 16-bit floating-point values. The results are packed into a single unsigned integer.
  25956. *
  25957. * @tsl
  25958. * @function
  25959. * @param {Node<vec2>} value - The 2-component vector to be packed
  25960. * @returns {Node}
  25961. */
  25962. const packHalf2x16 = /*@__PURE__*/ nodeProxyIntent( PackFloatNode, 'float16' ).setParameterLength( 1 );
  25963. /**
  25964. * This node represents an operation that unpacks values from a 32-bit unsigned integer, reinterpreting the results as a floating-point vector
  25965. *
  25966. * @augments TempNode
  25967. */
  25968. class UnpackFloatNode extends TempNode {
  25969. static get type() {
  25970. return 'UnpackFloatNode';
  25971. }
  25972. /**
  25973. *
  25974. * @param {'snorm' | 'unorm' | 'float16'} encoding - The numeric encoding that describes how the integer values are mapped to the float range
  25975. * @param {Node} uintNode - The uint node to be unpacked
  25976. */
  25977. constructor( encoding, uintNode ) {
  25978. super();
  25979. /**
  25980. * The unsigned integer to be unpacked.
  25981. *
  25982. * @type {Node}
  25983. */
  25984. this.uintNode = uintNode;
  25985. /**
  25986. * The numeric encoding.
  25987. *
  25988. * @type {string}
  25989. */
  25990. this.encoding = encoding;
  25991. /**
  25992. * This flag can be used for type testing.
  25993. *
  25994. * @type {boolean}
  25995. * @readonly
  25996. * @default true
  25997. */
  25998. this.isUnpackFloatNode = true;
  25999. }
  26000. generateNodeType() {
  26001. return 'vec2';
  26002. }
  26003. generate( builder ) {
  26004. const inputType = this.uintNode.getNodeType( builder );
  26005. return `${ builder.getFloatUnpackingMethod( this.encoding ) }(${ this.uintNode.build( builder, inputType )})`;
  26006. }
  26007. }
  26008. /**
  26009. * Unpacks a 32-bit unsigned integer into two 16-bit values, interpreted as normalized signed integers. Returns a vec2 with both values.
  26010. *
  26011. * @tsl
  26012. * @function
  26013. * @param {Node<uint>} value - The unsigned integer to be unpacked
  26014. * @returns {Node}
  26015. */
  26016. const unpackSnorm2x16 = /*@__PURE__*/ nodeProxyIntent( UnpackFloatNode, 'snorm' ).setParameterLength( 1 );
  26017. /**
  26018. * Unpacks a 32-bit unsigned integer into two 16-bit values, interpreted as normalized unsigned integers. Returns a vec2 with both values.
  26019. *
  26020. * @tsl
  26021. * @function
  26022. * @param {Node<uint>} value - The unsigned integer to be unpacked
  26023. * @returns {Node}
  26024. */
  26025. const unpackUnorm2x16 = /*@__PURE__*/ nodeProxyIntent( UnpackFloatNode, 'unorm' ).setParameterLength( 1 );
  26026. /**
  26027. * Unpacks a 32-bit unsigned integer into two 16-bit values, interpreted as 16-bit floating-point numbers. Returns a vec2 with both values.
  26028. *
  26029. * @tsl
  26030. * @function
  26031. * @param {Node<uint>} value - The unsigned integer to be unpacked
  26032. * @returns {Node}
  26033. */
  26034. const unpackHalf2x16 = /*@__PURE__*/ nodeProxyIntent( UnpackFloatNode, 'float16' ).setParameterLength( 1 );
  26035. // https://github.com/cabbibo/glsl-tri-noise-3d
  26036. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  26037. return x.fract().sub( .5 ).abs();
  26038. } ).setLayout( {
  26039. name: 'tri',
  26040. type: 'float',
  26041. inputs: [
  26042. { name: 'x', type: 'float' }
  26043. ]
  26044. } );
  26045. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  26046. 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. ) ) ) ) );
  26047. } ).setLayout( {
  26048. name: 'tri3',
  26049. type: 'vec3',
  26050. inputs: [
  26051. { name: 'p', type: 'vec3' }
  26052. ]
  26053. } );
  26054. /**
  26055. * Generates a noise value from the given position, speed and time parameters.
  26056. *
  26057. * @tsl
  26058. * @function
  26059. * @param {Node<vec3>} position - The position.
  26060. * @param {Node<float>} speed - The speed.
  26061. * @param {Node<float>} time - The time.
  26062. * @return {Node<float>} The generated noise.
  26063. */
  26064. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  26065. const p = vec3( position ).toVar();
  26066. const z = float( 1.4 ).toVar();
  26067. const rz = float( 0.0 ).toVar();
  26068. const bp = vec3( p ).toVar();
  26069. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  26070. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  26071. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  26072. bp.mulAssign( 1.8 );
  26073. z.mulAssign( 1.5 );
  26074. p.mulAssign( 1.2 );
  26075. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  26076. rz.addAssign( t.div( z ) );
  26077. bp.addAssign( 0.14 );
  26078. } );
  26079. return rz;
  26080. } ).setLayout( {
  26081. name: 'triNoise3D',
  26082. type: 'float',
  26083. inputs: [
  26084. { name: 'position', type: 'vec3' },
  26085. { name: 'speed', type: 'float' },
  26086. { name: 'time', type: 'float' }
  26087. ]
  26088. } );
  26089. /**
  26090. * This class allows to define multiple overloaded versions
  26091. * of the same function. Depending on the parameters of the function
  26092. * call, the node picks the best-fit overloaded version.
  26093. *
  26094. * @augments Node
  26095. */
  26096. class FunctionOverloadingNode extends Node {
  26097. static get type() {
  26098. return 'FunctionOverloadingNode';
  26099. }
  26100. /**
  26101. * Constructs a new function overloading node.
  26102. *
  26103. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  26104. * @param {...Node} parametersNodes - A list of parameter nodes.
  26105. */
  26106. constructor( functionNodes = [], ...parametersNodes ) {
  26107. super();
  26108. /**
  26109. * Array of `Fn` function definitions.
  26110. *
  26111. * @type {Array<Function>}
  26112. */
  26113. this.functionNodes = functionNodes;
  26114. /**
  26115. * A list of parameter nodes.
  26116. *
  26117. * @type {Array<Node>}
  26118. */
  26119. this.parametersNodes = parametersNodes;
  26120. /**
  26121. * The selected overloaded function call.
  26122. *
  26123. * @private
  26124. * @type {ShaderCallNodeInternal}
  26125. */
  26126. this._candidateFn = null;
  26127. /**
  26128. * This node is marked as global.
  26129. *
  26130. * @type {boolean}
  26131. * @default true
  26132. */
  26133. this.global = true;
  26134. }
  26135. /**
  26136. * This method is overwritten since the node type is inferred from
  26137. * the function's return type.
  26138. *
  26139. * @param {NodeBuilder} builder - The current node builder.
  26140. * @return {string} The node type.
  26141. */
  26142. generateNodeType( builder ) {
  26143. const candidateFn = this.getCandidateFn( builder );
  26144. return candidateFn.shaderNode.layout.type;
  26145. }
  26146. /**
  26147. * Returns the candidate function for the current parameters.
  26148. *
  26149. * @param {NodeBuilder} builder - The current node builder.
  26150. * @return {FunctionNode} The candidate function.
  26151. */
  26152. getCandidateFn( builder ) {
  26153. const params = this.parametersNodes;
  26154. let candidateFn = this._candidateFn;
  26155. if ( candidateFn === null ) {
  26156. let bestCandidateFn = null;
  26157. let bestScore = -1;
  26158. for ( const functionNode of this.functionNodes ) {
  26159. const shaderNode = functionNode.shaderNode;
  26160. const layout = shaderNode.layout;
  26161. if ( layout === null ) {
  26162. throw new Error( 'THREE.FunctionOverloadingNode: FunctionNode must be a layout.' );
  26163. }
  26164. const inputs = layout.inputs;
  26165. if ( params.length === inputs.length ) {
  26166. let currentScore = 0;
  26167. for ( let i = 0; i < params.length; i ++ ) {
  26168. const param = params[ i ];
  26169. const input = inputs[ i ];
  26170. if ( param.getNodeType( builder ) === input.type ) {
  26171. currentScore ++;
  26172. }
  26173. }
  26174. if ( currentScore > bestScore ) {
  26175. bestCandidateFn = functionNode;
  26176. bestScore = currentScore;
  26177. }
  26178. }
  26179. }
  26180. this._candidateFn = candidateFn = bestCandidateFn;
  26181. }
  26182. return candidateFn;
  26183. }
  26184. /**
  26185. * Sets up the node for the current parameters.
  26186. *
  26187. * @param {NodeBuilder} builder - The current node builder.
  26188. * @return {Node} The setup node.
  26189. */
  26190. setup( builder ) {
  26191. const candidateFn = this.getCandidateFn( builder );
  26192. return candidateFn( ...this.parametersNodes );
  26193. }
  26194. }
  26195. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  26196. /**
  26197. * TSL function for creating a function overloading node.
  26198. *
  26199. * @tsl
  26200. * @function
  26201. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  26202. * @returns {FunctionOverloadingNode}
  26203. */
  26204. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  26205. /**
  26206. * Represents the elapsed time in seconds.
  26207. *
  26208. * @tsl
  26209. * @type {UniformNode<float>}
  26210. */
  26211. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  26212. /**
  26213. * Represents the delta time in seconds.
  26214. *
  26215. * @tsl
  26216. * @type {UniformNode<float>}
  26217. */
  26218. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  26219. /**
  26220. * Represents the current frame ID.
  26221. *
  26222. * @tsl
  26223. * @type {UniformNode<uint>}
  26224. */
  26225. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  26226. /**
  26227. * Generates a sine wave oscillation based on a timer.
  26228. *
  26229. * @tsl
  26230. * @function
  26231. * @param {Node<float>} t - The timer to generate the oscillation with.
  26232. * @return {Node<float>} The oscillation node.
  26233. */
  26234. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  26235. /**
  26236. * Generates a square wave oscillation based on a timer.
  26237. *
  26238. * @tsl
  26239. * @function
  26240. * @param {Node<float>} t - The timer to generate the oscillation with.
  26241. * @return {Node<float>} The oscillation node.
  26242. */
  26243. const oscSquare = ( t = time ) => t.fract().round();
  26244. /**
  26245. * Generates a triangle wave oscillation based on a timer.
  26246. *
  26247. * @tsl
  26248. * @function
  26249. * @param {Node<float>} t - The timer to generate the oscillation with.
  26250. * @return {Node<float>} The oscillation node.
  26251. */
  26252. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  26253. /**
  26254. * Generates a sawtooth wave oscillation based on a timer.
  26255. *
  26256. * @tsl
  26257. * @function
  26258. * @param {Node<float>} t - The timer to generate the oscillation with.
  26259. * @return {Node<float>} The oscillation node.
  26260. */
  26261. const oscSawtooth = ( t = time ) => t.fract();
  26262. /**
  26263. * Replaces the default UV coordinates used in texture lookups.
  26264. *
  26265. * ```js
  26266. *material.contextNode = replaceDefaultUV( ( textureNode ) => {
  26267. *
  26268. * // ...
  26269. * return customUVCoordinates;
  26270. *
  26271. *} );
  26272. *```
  26273. *
  26274. * @tsl
  26275. * @function
  26276. * @param {function(Node):Node<vec2>|Node<vec2>} callback - A callback that receives the texture node
  26277. * and must return the new uv coordinates.
  26278. * @param {Node} [node=null] - An optional node to which the context will be applied.
  26279. * @return {ContextNode} A context node that replaces the default UV coordinates.
  26280. */
  26281. function replaceDefaultUV( callback, node = null ) {
  26282. const getUV = typeof callback === 'function' ? callback : () => callback;
  26283. return context( node, { getUV } );
  26284. }
  26285. /**
  26286. * Rotates the given uv coordinates around a center point
  26287. *
  26288. * @tsl
  26289. * @function
  26290. * @param {Node<vec2>} uv - The uv coordinates.
  26291. * @param {Node<float>} rotation - The rotation defined in radians.
  26292. * @param {Node<vec2>} center - The center of rotation
  26293. * @return {Node<vec2>} The rotated uv coordinates.
  26294. */
  26295. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  26296. return rotate( uv.sub( center ), rotation ).add( center );
  26297. } );
  26298. /**
  26299. * Applies a spherical warping effect to the given uv coordinates.
  26300. *
  26301. * @tsl
  26302. * @function
  26303. * @param {Node<vec2>} uv - The uv coordinates.
  26304. * @param {Node<float>} strength - The strength of the effect.
  26305. * @param {Node<vec2>} center - The center point
  26306. * @return {Node<vec2>} The updated uv coordinates.
  26307. */
  26308. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  26309. const delta = uv.sub( center );
  26310. const delta2 = delta.dot( delta );
  26311. const delta4 = delta2.mul( delta2 );
  26312. const deltaOffset = delta4.mul( strength );
  26313. return uv.add( delta.mul( deltaOffset ) );
  26314. } );
  26315. /**
  26316. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  26317. * oriented always towards the camera.
  26318. *
  26319. * ```js
  26320. * material.vertexNode = billboarding();
  26321. * ```
  26322. *
  26323. * @tsl
  26324. * @function
  26325. * @param {Object} config - The configuration object.
  26326. * @param {?Node<vec3>} [config.position=null] - Can be used to define the vertex positions in world space.
  26327. * @param {boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  26328. * @param {boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  26329. * @return {Node<vec3>} The updated vertex position in clip space.
  26330. */
  26331. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  26332. let worldMatrix;
  26333. if ( position !== null ) {
  26334. worldMatrix = modelWorldMatrix.toVar();
  26335. worldMatrix[ 3 ][ 0 ] = position.x;
  26336. worldMatrix[ 3 ][ 1 ] = position.y;
  26337. worldMatrix[ 3 ][ 2 ] = position.z;
  26338. } else {
  26339. worldMatrix = modelWorldMatrix;
  26340. }
  26341. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  26342. if ( defined( horizontal ) ) {
  26343. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  26344. modelViewMatrix[ 0 ][ 1 ] = 0;
  26345. modelViewMatrix[ 0 ][ 2 ] = 0;
  26346. }
  26347. if ( defined( vertical ) ) {
  26348. modelViewMatrix[ 1 ][ 0 ] = 0;
  26349. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  26350. modelViewMatrix[ 1 ][ 2 ] = 0;
  26351. }
  26352. modelViewMatrix[ 2 ][ 0 ] = 0;
  26353. modelViewMatrix[ 2 ][ 1 ] = 0;
  26354. modelViewMatrix[ 2 ][ 2 ] = 1;
  26355. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  26356. } );
  26357. /**
  26358. * A special version of a screen uv function that involves a depth comparison
  26359. * when computing the final uvs. The function mitigates visual errors when
  26360. * using viewport texture nodes for refraction purposes. Without this function
  26361. * objects in front of a refractive surface might appear on the refractive surface
  26362. * which is incorrect.
  26363. *
  26364. * @tsl
  26365. * @function
  26366. * @param {?Node<vec2>} uv - Optional uv coordinates. By default `screenUV` is used.
  26367. * @return {Node<vec2>} The update uv coordinates.
  26368. */
  26369. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  26370. const depth = linearDepth();
  26371. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  26372. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  26373. return finalUV;
  26374. } );
  26375. /**
  26376. * TSL function for computing texture coordinates for animated sprite sheets.
  26377. *
  26378. * ```js
  26379. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  26380. *
  26381. * material.colorNode = texture( spriteSheet, uvNode );
  26382. * ```
  26383. *
  26384. * @tsl
  26385. * @function
  26386. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  26387. * @param {?Node<vec2>} [uvNode=uv()] - The uv node.
  26388. * @param {?Node<float>} [frameNode=float(0)] - The node that defines the current frame/sprite.
  26389. * @returns {Node<vec2>}
  26390. */
  26391. const spritesheetUV = /*@__PURE__*/ Fn( ( [ countNode, uvNode = uv$1(), frameNode = float( 0 ) ] ) => {
  26392. const width = countNode.x;
  26393. const height = countNode.y;
  26394. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  26395. const column = frameNum.mod( width );
  26396. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  26397. const scale = countNode.reciprocal();
  26398. const uvFrameOffset = vec2( column, row );
  26399. return uvNode.add( uvFrameOffset ).mul( scale );
  26400. } );
  26401. /**
  26402. * TSL function for creating a triplanar textures node.
  26403. *
  26404. * Can be used for triplanar texture mapping.
  26405. *
  26406. * ```js
  26407. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  26408. * ```
  26409. *
  26410. * @tsl
  26411. * @function
  26412. * @param {Node} textureXNode - First texture node.
  26413. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  26414. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  26415. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  26416. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  26417. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  26418. * @returns {Node<vec4>}
  26419. */
  26420. const triplanarTextures = /*@__PURE__*/ Fn( ( [ textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ] ) => {
  26421. // Reference: https://github.com/keijiro/StandardTriplanar
  26422. // Blending factor of triplanar mapping
  26423. let bf = normalNode.abs().normalize();
  26424. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  26425. // Triplanar mapping
  26426. const tx = positionNode.yz.mul( scaleNode );
  26427. const ty = positionNode.zx.mul( scaleNode );
  26428. const tz = positionNode.xy.mul( scaleNode );
  26429. // Base color
  26430. const textureX = textureXNode.value;
  26431. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  26432. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  26433. const cx = texture( textureX, tx ).mul( bf.x );
  26434. const cy = texture( textureY, ty ).mul( bf.y );
  26435. const cz = texture( textureZ, tz ).mul( bf.z );
  26436. return add( cx, cy, cz );
  26437. } );
  26438. /**
  26439. * TSL function for creating a triplanar textures node.
  26440. *
  26441. * @tsl
  26442. * @function
  26443. * @param {Node} textureXNode - First texture node.
  26444. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  26445. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  26446. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  26447. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  26448. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  26449. * @returns {Node<vec4>}
  26450. */
  26451. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  26452. const _reflectorPlane = new Plane();
  26453. const _normal = new Vector3();
  26454. const _reflectorWorldPosition = new Vector3();
  26455. const _cameraWorldPosition = new Vector3();
  26456. const _rotationMatrix = new Matrix4();
  26457. const _lookAtPosition = new Vector3( 0, 0, -1 );
  26458. const clipPlane = new Vector4();
  26459. const _view = new Vector3();
  26460. const _target = new Vector3();
  26461. const _q = new Vector4();
  26462. const _size$2 = new Vector2();
  26463. const _defaultRT = new RenderTarget();
  26464. const _defaultUV = screenUV.flipX();
  26465. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  26466. let _inReflector = false;
  26467. /**
  26468. * This node can be used to implement mirror-like flat reflective surfaces.
  26469. *
  26470. * ```js
  26471. * const groundReflector = reflector();
  26472. * material.colorNode = groundReflector;
  26473. *
  26474. * const plane = new Mesh( geometry, material );
  26475. * plane.add( groundReflector.target );
  26476. * ```
  26477. *
  26478. * @augments TextureNode
  26479. */
  26480. class ReflectorNode extends TextureNode {
  26481. static get type() {
  26482. return 'ReflectorNode';
  26483. }
  26484. /**
  26485. * Constructs a new reflector node.
  26486. *
  26487. * @param {Object} [parameters={}] - An object holding configuration parameters.
  26488. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  26489. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  26490. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  26491. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  26492. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  26493. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  26494. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  26495. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  26496. */
  26497. constructor( parameters = {} ) {
  26498. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  26499. /**
  26500. * A reference to the internal reflector base node which holds the actual implementation.
  26501. *
  26502. * @private
  26503. * @type {ReflectorBaseNode}
  26504. * @default ReflectorBaseNode
  26505. */
  26506. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  26507. /**
  26508. * A reference to the internal depth node.
  26509. *
  26510. * @private
  26511. * @type {?Node}
  26512. * @default null
  26513. */
  26514. this._depthNode = null;
  26515. this.setUpdateMatrix( false );
  26516. }
  26517. /**
  26518. * A reference to the internal reflector node.
  26519. *
  26520. * @type {ReflectorBaseNode}
  26521. */
  26522. get reflector() {
  26523. return this._reflectorBaseNode;
  26524. }
  26525. /**
  26526. * A reference to 3D object the reflector is linked to.
  26527. *
  26528. * @type {Object3D}
  26529. */
  26530. get target() {
  26531. return this._reflectorBaseNode.target;
  26532. }
  26533. /**
  26534. * Returns a node representing the mirror's depth. That can be used
  26535. * to implement more advanced reflection effects like distance attenuation.
  26536. *
  26537. * @return {Node} The depth node.
  26538. */
  26539. getDepthNode() {
  26540. if ( this._depthNode === null ) {
  26541. if ( this._reflectorBaseNode.depth !== true ) {
  26542. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  26543. }
  26544. this._depthNode = new ReflectorNode( {
  26545. defaultTexture: _defaultRT.depthTexture,
  26546. reflector: this._reflectorBaseNode
  26547. } );
  26548. }
  26549. return this._depthNode;
  26550. }
  26551. setup( builder ) {
  26552. // ignore if used in post-processing
  26553. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  26554. return super.setup( builder );
  26555. }
  26556. clone() {
  26557. const newNode = new this.constructor( this.reflectorNode );
  26558. newNode.uvNode = this.uvNode;
  26559. newNode.levelNode = this.levelNode;
  26560. newNode.biasNode = this.biasNode;
  26561. newNode.sampler = this.sampler;
  26562. newNode.depthNode = this.depthNode;
  26563. newNode.compareNode = this.compareNode;
  26564. newNode.gradNode = this.gradNode;
  26565. newNode.gatherNode = this.gatherNode;
  26566. newNode.offsetNode = this.offsetNode;
  26567. newNode._reflectorBaseNode = this._reflectorBaseNode;
  26568. return newNode;
  26569. }
  26570. /**
  26571. * Frees internal resources. Should be called when the node is no longer in use.
  26572. */
  26573. dispose() {
  26574. super.dispose();
  26575. this._reflectorBaseNode.dispose();
  26576. }
  26577. }
  26578. /**
  26579. * Holds the actual implementation of the reflector.
  26580. *
  26581. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  26582. * in `ReflectorNode`, see #29619.
  26583. *
  26584. * @private
  26585. * @augments Node
  26586. */
  26587. class ReflectorBaseNode extends Node {
  26588. static get type() {
  26589. return 'ReflectorBaseNode';
  26590. }
  26591. /**
  26592. * Constructs a new reflector base node.
  26593. *
  26594. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  26595. * @param {Object} [parameters={}] - An object holding configuration parameters.
  26596. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  26597. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  26598. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  26599. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  26600. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  26601. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  26602. */
  26603. constructor( textureNode, parameters = {} ) {
  26604. super();
  26605. const {
  26606. target = new Object3D(),
  26607. resolutionScale = 1,
  26608. generateMipmaps = false,
  26609. bounces = true,
  26610. depth = false,
  26611. samples = 0
  26612. } = parameters;
  26613. /**
  26614. * Represents the rendered reflections as a texture node.
  26615. *
  26616. * @type {TextureNode}
  26617. */
  26618. this.textureNode = textureNode;
  26619. /**
  26620. * The 3D object the reflector is linked to.
  26621. *
  26622. * @type {Object3D}
  26623. * @default {new Object3D()}
  26624. */
  26625. this.target = target;
  26626. /**
  26627. * The resolution scale.
  26628. *
  26629. * @type {number}
  26630. * @default {1}
  26631. */
  26632. this.resolutionScale = resolutionScale;
  26633. if ( parameters.resolution !== undefined ) {
  26634. warnOnce( 'ReflectorNode: The "resolution" parameter has been renamed to "resolutionScale".' ); // @deprecated r180
  26635. this.resolutionScale = parameters.resolution;
  26636. }
  26637. /**
  26638. * Whether mipmaps should be generated or not.
  26639. *
  26640. * @type {boolean}
  26641. * @default {false}
  26642. */
  26643. this.generateMipmaps = generateMipmaps;
  26644. /**
  26645. * Whether reflectors can render other reflector nodes or not.
  26646. *
  26647. * @type {boolean}
  26648. * @default {true}
  26649. */
  26650. this.bounces = bounces;
  26651. /**
  26652. * Whether depth data should be generated or not.
  26653. *
  26654. * @type {boolean}
  26655. * @default {false}
  26656. */
  26657. this.depth = depth;
  26658. /**
  26659. * The number of anti-aliasing samples for the render-target
  26660. *
  26661. * @type {number}
  26662. * @default {0}
  26663. */
  26664. this.samples = samples;
  26665. /**
  26666. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  26667. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  26668. *
  26669. * @type {string}
  26670. * @default 'render'
  26671. */
  26672. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  26673. /**
  26674. * Weak map for managing virtual cameras.
  26675. *
  26676. * @type {WeakMap<Camera, Camera>}
  26677. */
  26678. this.virtualCameras = new WeakMap();
  26679. /**
  26680. * Weak map for managing render targets.
  26681. *
  26682. * @type {Map<Camera, RenderTarget>}
  26683. */
  26684. this.renderTargets = new Map();
  26685. /**
  26686. * Force render even if reflector is facing away from camera.
  26687. *
  26688. * @type {boolean}
  26689. * @default {false}
  26690. */
  26691. this.forceUpdate = false;
  26692. /**
  26693. * Whether the reflector has been rendered or not.
  26694. *
  26695. * When the reflector is facing away from the camera,
  26696. * this flag is set to `false` and the texture will be empty(black).
  26697. *
  26698. * @type {boolean}
  26699. * @default {false}
  26700. */
  26701. this.hasOutput = false;
  26702. }
  26703. /**
  26704. * Updates the resolution of the internal render target.
  26705. *
  26706. * @private
  26707. * @param {RenderTarget} renderTarget - The render target to resize.
  26708. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  26709. */
  26710. _updateResolution( renderTarget, renderer ) {
  26711. const resolution = this.resolutionScale;
  26712. renderer.getDrawingBufferSize( _size$2 );
  26713. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  26714. }
  26715. setup( builder ) {
  26716. this._updateResolution( _defaultRT, builder.renderer );
  26717. return super.setup( builder );
  26718. }
  26719. /**
  26720. * Frees internal resources. Should be called when the node is no longer in use.
  26721. */
  26722. dispose() {
  26723. super.dispose();
  26724. for ( const renderTarget of this.renderTargets.values() ) {
  26725. renderTarget.dispose();
  26726. }
  26727. }
  26728. /**
  26729. * Returns a virtual camera for the given camera. The virtual camera is used to
  26730. * render the scene from the reflector's view so correct reflections can be produced.
  26731. *
  26732. * @param {Camera} camera - The scene's camera.
  26733. * @return {Camera} The corresponding virtual camera.
  26734. */
  26735. getVirtualCamera( camera ) {
  26736. let virtualCamera = this.virtualCameras.get( camera );
  26737. if ( virtualCamera === undefined ) {
  26738. virtualCamera = camera.clone();
  26739. this.virtualCameras.set( camera, virtualCamera );
  26740. }
  26741. return virtualCamera;
  26742. }
  26743. /**
  26744. * Returns a render target for the given camera. The reflections are rendered
  26745. * into this render target.
  26746. *
  26747. * @param {Camera} camera - The scene's camera.
  26748. * @return {RenderTarget} The render target.
  26749. */
  26750. getRenderTarget( camera ) {
  26751. let renderTarget = this.renderTargets.get( camera );
  26752. if ( renderTarget === undefined ) {
  26753. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType, samples: this.samples } );
  26754. if ( this.generateMipmaps === true ) {
  26755. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  26756. renderTarget.texture.generateMipmaps = true;
  26757. }
  26758. if ( this.depth === true ) {
  26759. renderTarget.depthTexture = new DepthTexture();
  26760. }
  26761. this.renderTargets.set( camera, renderTarget );
  26762. }
  26763. return renderTarget;
  26764. }
  26765. updateBefore( frame ) {
  26766. if ( this.bounces === false && _inReflector ) return false;
  26767. _inReflector = true;
  26768. const { scene, camera, renderer, material } = frame;
  26769. const { target } = this;
  26770. const virtualCamera = this.getVirtualCamera( camera );
  26771. const renderTarget = this.getRenderTarget( virtualCamera );
  26772. renderer.getDrawingBufferSize( _size$2 );
  26773. this._updateResolution( renderTarget, renderer );
  26774. //
  26775. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  26776. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  26777. _rotationMatrix.extractRotation( target.matrixWorld );
  26778. _normal.set( 0, 0, 1 );
  26779. _normal.applyMatrix4( _rotationMatrix );
  26780. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  26781. // Avoid rendering when reflector is facing away unless forcing an update
  26782. const isFacingAway = _view.dot( _normal ) > 0;
  26783. let needsClear = false;
  26784. if ( isFacingAway === true && this.forceUpdate === false ) {
  26785. if ( this.hasOutput === false ) {
  26786. _inReflector = false;
  26787. return;
  26788. }
  26789. needsClear = true;
  26790. }
  26791. _view.reflect( _normal ).negate();
  26792. _view.add( _reflectorWorldPosition );
  26793. _rotationMatrix.extractRotation( camera.matrixWorld );
  26794. _lookAtPosition.set( 0, 0, -1 );
  26795. _lookAtPosition.applyMatrix4( _rotationMatrix );
  26796. _lookAtPosition.add( _cameraWorldPosition );
  26797. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  26798. _target.reflect( _normal ).negate();
  26799. _target.add( _reflectorWorldPosition );
  26800. //
  26801. virtualCamera.coordinateSystem = camera.coordinateSystem;
  26802. virtualCamera.position.copy( _view );
  26803. virtualCamera.up.set( 0, 1, 0 );
  26804. virtualCamera.up.applyMatrix4( _rotationMatrix );
  26805. virtualCamera.up.reflect( _normal );
  26806. virtualCamera.lookAt( _target );
  26807. virtualCamera.near = camera.near;
  26808. virtualCamera.far = camera.far;
  26809. virtualCamera.updateMatrixWorld();
  26810. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  26811. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  26812. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  26813. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  26814. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  26815. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  26816. const projectionMatrix = virtualCamera.projectionMatrix;
  26817. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  26818. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  26819. _q.z = -1;
  26820. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  26821. // Calculate the scaled plane vector
  26822. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  26823. const clipBias = 0;
  26824. // Replacing the third row of the projection matrix
  26825. projectionMatrix.elements[ 2 ] = clipPlane.x;
  26826. projectionMatrix.elements[ 6 ] = clipPlane.y;
  26827. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  26828. projectionMatrix.elements[ 14 ] = clipPlane.w;
  26829. //
  26830. this.textureNode.value = renderTarget.texture;
  26831. if ( this.depth === true ) {
  26832. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  26833. }
  26834. material.visible = false;
  26835. const currentRenderTarget = renderer.getRenderTarget();
  26836. const currentMRT = renderer.getMRT();
  26837. const currentAutoClear = renderer.autoClear;
  26838. renderer.setMRT( null );
  26839. renderer.setRenderTarget( renderTarget );
  26840. renderer.autoClear = true;
  26841. const previousName = scene.name;
  26842. scene.name = ( scene.name || 'Scene' ) + ' [ Reflector ]'; // TODO: Add bounce index
  26843. if ( needsClear ) {
  26844. renderer.clear();
  26845. this.hasOutput = false;
  26846. } else {
  26847. renderer.render( scene, virtualCamera );
  26848. this.hasOutput = true;
  26849. }
  26850. scene.name = previousName;
  26851. renderer.setMRT( currentMRT );
  26852. renderer.setRenderTarget( currentRenderTarget );
  26853. renderer.autoClear = currentAutoClear;
  26854. material.visible = true;
  26855. _inReflector = false;
  26856. this.forceUpdate = false;
  26857. }
  26858. /**
  26859. * The resolution scale.
  26860. *
  26861. * @deprecated
  26862. * @type {number}
  26863. * @default {1}
  26864. */
  26865. get resolution() {
  26866. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  26867. return this.resolutionScale;
  26868. }
  26869. set resolution( value ) {
  26870. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  26871. this.resolutionScale = value;
  26872. }
  26873. }
  26874. /**
  26875. * TSL function for creating a reflector node.
  26876. *
  26877. * @tsl
  26878. * @function
  26879. * @param {Object} [parameters={}] - An object holding configuration parameters.
  26880. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  26881. * @param {number} [parameters.resolution=1] - The resolution scale.
  26882. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  26883. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  26884. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  26885. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  26886. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  26887. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  26888. * @returns {ReflectorNode}
  26889. */
  26890. const reflector = ( parameters ) => new ReflectorNode( parameters );
  26891. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  26892. /**
  26893. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  26894. *
  26895. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  26896. *
  26897. * @private
  26898. * @augments BufferGeometry
  26899. */
  26900. class QuadGeometry extends BufferGeometry {
  26901. /**
  26902. * Constructs a new quad geometry.
  26903. *
  26904. * @param {boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  26905. */
  26906. constructor( flipY = false ) {
  26907. super();
  26908. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  26909. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  26910. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  26911. }
  26912. }
  26913. const _geometry = /*@__PURE__*/ new QuadGeometry();
  26914. const _vertexNode = /*@__PURE__*/ vec4(
  26915. array( [ -1, -1, 3.0 ] ).element( vertexIndex ),
  26916. array( [ 3.0, -1, -1 ] ).element( vertexIndex ),
  26917. 0.0,
  26918. 1.0
  26919. );
  26920. /**
  26921. * This module is a helper for passes which need to render a full
  26922. * screen effect which is quite common in context of post processing.
  26923. *
  26924. * The intended usage is to reuse a single quad mesh for rendering
  26925. * subsequent passes by just reassigning the `material` reference.
  26926. *
  26927. * Note: This module can only be used with `WebGPURenderer`.
  26928. *
  26929. * @augments Mesh
  26930. */
  26931. class QuadMesh extends Mesh {
  26932. /**
  26933. * Constructs a new quad mesh.
  26934. *
  26935. * @param {NodeMaterial} material - The material to render the quad mesh with.
  26936. */
  26937. constructor( material ) {
  26938. super( _geometry, material );
  26939. /**
  26940. * The camera to render the quad mesh with.
  26941. *
  26942. * @type {OrthographicCamera}
  26943. * @readonly
  26944. */
  26945. this.camera = _camera;
  26946. /**
  26947. * This flag can be used for type testing.
  26948. *
  26949. * @type {boolean}
  26950. * @readonly
  26951. * @default true
  26952. */
  26953. this.isQuadMesh = true;
  26954. }
  26955. /**
  26956. * Async version of `render()`.
  26957. *
  26958. * @async
  26959. * @deprecated
  26960. * @param {Renderer} renderer - The renderer.
  26961. * @return {Promise} A Promise that resolves when the render has been finished.
  26962. */
  26963. async renderAsync( renderer ) {
  26964. warnOnce( 'QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  26965. await renderer.init();
  26966. renderer.render( this, _camera );
  26967. }
  26968. /**
  26969. * Renders the quad mesh
  26970. *
  26971. * @param {Renderer} renderer - The renderer.
  26972. */
  26973. render( renderer ) {
  26974. const previousVertexNode = this.material.vertexNode;
  26975. this.material.vertexNode = _vertexNode;
  26976. renderer.render( this, _camera );
  26977. this.material.vertexNode = previousVertexNode;
  26978. }
  26979. }
  26980. const _size$1 = /*@__PURE__*/ new Vector2();
  26981. /**
  26982. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  26983. * This module is especially relevant in context of post processing where certain nodes require
  26984. * texture input for their effects. With the helper function `convertToTexture()` which is based
  26985. * on this module, the node system can automatically ensure texture input if required.
  26986. *
  26987. * @augments TextureNode
  26988. */
  26989. class RTTNode extends TextureNode {
  26990. static get type() {
  26991. return 'RTTNode';
  26992. }
  26993. /**
  26994. * Constructs a new RTT node.
  26995. *
  26996. * @param {Node} node - The node to render a texture with.
  26997. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  26998. * @param {?number} [height=null] - The height of the internal render target.
  26999. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  27000. */
  27001. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  27002. const renderTarget = new RenderTarget( width, height, options );
  27003. super( renderTarget.texture, uv$1() );
  27004. /**
  27005. * This flag can be used for type testing.
  27006. *
  27007. * @type {boolean}
  27008. * @readonly
  27009. * @default true
  27010. */
  27011. this.isRTTNode = true;
  27012. /**
  27013. * The node to render a texture with.
  27014. *
  27015. * @type {Node}
  27016. */
  27017. this.node = node;
  27018. /**
  27019. * The width of the internal render target.
  27020. * If not width is applied, the render target is automatically resized.
  27021. *
  27022. * @type {?number}
  27023. * @default null
  27024. */
  27025. this.width = width;
  27026. /**
  27027. * The height of the internal render target.
  27028. *
  27029. * @type {?number}
  27030. * @default null
  27031. */
  27032. this.height = height;
  27033. /**
  27034. * The render target
  27035. *
  27036. * @type {RenderTarget}
  27037. */
  27038. this.renderTarget = renderTarget;
  27039. /**
  27040. * Whether the texture requires an update or not.
  27041. *
  27042. * @type {boolean}
  27043. * @default true
  27044. */
  27045. this.textureNeedsUpdate = true;
  27046. /**
  27047. * Whether the texture should automatically be updated or not.
  27048. *
  27049. * @type {boolean}
  27050. * @default true
  27051. */
  27052. this.autoUpdate = true;
  27053. /**
  27054. * The resolution scale
  27055. *
  27056. * @private
  27057. * @type {number}
  27058. * @default 1
  27059. */
  27060. this._resolutionScale = 1;
  27061. /**
  27062. * The node which is used with the quad mesh for RTT.
  27063. *
  27064. * @private
  27065. * @type {Node}
  27066. * @default null
  27067. */
  27068. this._rttNode = null;
  27069. /**
  27070. * The internal quad mesh for RTT.
  27071. *
  27072. * @private
  27073. * @type {QuadMesh}
  27074. */
  27075. this._quadMesh = new QuadMesh( new NodeMaterial() );
  27076. /**
  27077. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  27078. * the texture once per render in its {@link RTTNode#updateBefore} method.
  27079. *
  27080. * @type {string}
  27081. * @default 'render'
  27082. */
  27083. this.updateBeforeType = NodeUpdateType.RENDER;
  27084. }
  27085. /**
  27086. * Whether the internal render target should automatically be resized or not.
  27087. *
  27088. * @type {boolean}
  27089. * @readonly
  27090. * @default true
  27091. */
  27092. get autoResize() {
  27093. return this.width === null;
  27094. }
  27095. setup( builder ) {
  27096. this._rttNode = this.node.context( builder.getSharedContext() );
  27097. this._quadMesh.material.name = 'RTT';
  27098. this._quadMesh.material.needsUpdate = true;
  27099. return super.setup( builder );
  27100. }
  27101. /**
  27102. * Sets the size of the internal render target
  27103. *
  27104. * @param {number} width - The width to set.
  27105. * @param {number} height - The width to set.
  27106. */
  27107. setSize( width, height ) {
  27108. const effectiveWidth = Math.floor( width * this._resolutionScale );
  27109. const effectiveHeight = Math.floor( height * this._resolutionScale );
  27110. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  27111. this.textureNeedsUpdate = true;
  27112. }
  27113. /**
  27114. * Sets the resolution scale.
  27115. * The resolution scale is a factor that is multiplied with the renderer's width and height.
  27116. *
  27117. * @param {number} resolutionScale - The resolution scale to set. A value of `1` means full resolution.
  27118. * @returns {RTTNode} A reference to this node.
  27119. */
  27120. setResolutionScale( resolutionScale ) {
  27121. this._resolutionScale = resolutionScale;
  27122. if ( this.autoResize === false ) {
  27123. this.setSize( this.width, this.height );
  27124. }
  27125. return this;
  27126. }
  27127. /**
  27128. * Gets the resolution scale.
  27129. *
  27130. * @returns {number} The resolution scale.
  27131. */
  27132. getResolutionScale() {
  27133. return this._resolutionScale;
  27134. }
  27135. updateBefore( { renderer } ) {
  27136. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  27137. this.textureNeedsUpdate = false;
  27138. //
  27139. const currentRenderTarget = renderer.getRenderTarget();
  27140. if ( this.autoResize === true ) {
  27141. const size = renderer.getDrawingBufferSize( _size$1 );
  27142. const effectiveWidth = Math.floor( size.width * this._resolutionScale );
  27143. const effectiveHeight = Math.floor( size.height * this._resolutionScale );
  27144. if ( effectiveWidth !== this.renderTarget.width || effectiveHeight !== this.renderTarget.height ) {
  27145. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  27146. this.textureNeedsUpdate = true;
  27147. }
  27148. }
  27149. //
  27150. let name = 'RTT';
  27151. if ( this.node.name ) {
  27152. name = this.node.name + ' [ ' + name + ' ]';
  27153. }
  27154. this._quadMesh.material.fragmentNode = this._rttNode;
  27155. this._quadMesh.name = name;
  27156. //
  27157. renderer.setRenderTarget( this.renderTarget );
  27158. this._quadMesh.render( renderer );
  27159. renderer.setRenderTarget( currentRenderTarget );
  27160. }
  27161. clone() {
  27162. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  27163. newNode.sampler = this.sampler;
  27164. newNode.referenceNode = this;
  27165. return newNode;
  27166. }
  27167. }
  27168. /**
  27169. * TSL function for creating a RTT node.
  27170. *
  27171. * @tsl
  27172. * @function
  27173. * @param {Node} node - The node to render a texture with.
  27174. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  27175. * @param {?number} [height=null] - The height of the internal render target.
  27176. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  27177. * @returns {RTTNode}
  27178. */
  27179. const rtt = ( node, ...params ) => new RTTNode( nodeObject( node ), ...params );
  27180. /**
  27181. * TSL function for converting nodes to textures nodes.
  27182. *
  27183. * @tsl
  27184. * @function
  27185. * @param {Node} node - The node to render a texture with.
  27186. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  27187. * @param {?number} [height=null] - The height of the internal render target.
  27188. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  27189. * @returns {RTTNode}
  27190. */
  27191. const convertToTexture = ( node, ...params ) => {
  27192. if ( node.isSampleNode || node.isTextureNode ) return node;
  27193. if ( node.isPassNode ) return node.getTextureNode();
  27194. return rtt( node, ...params );
  27195. };
  27196. /**
  27197. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  27198. * depth value and the camera's inverse projection matrix.
  27199. *
  27200. * @tsl
  27201. * @function
  27202. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  27203. * @param {Node<float>} depth - The fragment's depth value.
  27204. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  27205. * @return {Node<vec3>} The fragments position in view space.
  27206. */
  27207. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  27208. let clipSpacePosition;
  27209. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  27210. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  27211. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  27212. } else {
  27213. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  27214. }
  27215. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  27216. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  27217. } );
  27218. /**
  27219. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  27220. * and the camera's projection matrix
  27221. *
  27222. * @tsl
  27223. * @function
  27224. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  27225. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  27226. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  27227. */
  27228. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  27229. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  27230. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  27231. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  27232. } );
  27233. /**
  27234. * Converts a clip-space position into a screen position expressed as uv coordinates.
  27235. *
  27236. * @tsl
  27237. * @function
  27238. * @param {Node<vec4>} clipPosition - The position in clip space.
  27239. * @return {Node<vec2>} The screen position expressed as uv coordinates.
  27240. */
  27241. const getScreenPositionFromClip = /*@__PURE__*/ Fn( ( [ clipPosition ] ) => {
  27242. const screen = clipPosition.xy.div( clipPosition.w ).mul( 0.5 ).add( 0.5 ).toVar();
  27243. return vec2( screen.x, screen.y.oneMinus() );
  27244. } ).setLayout( {
  27245. name: 'getScreenPositionFromClip',
  27246. type: 'vec2',
  27247. inputs: [
  27248. { name: 'clipPosition', type: 'vec4' }
  27249. ]
  27250. } );
  27251. /**
  27252. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  27253. * target is available or if flat surface normals are required.
  27254. *
  27255. * @tsl
  27256. * @function
  27257. * @param {Node<vec2>} uv - The texture coordinate.
  27258. * @param {DepthTexture} depthTexture - The depth texture.
  27259. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  27260. * @return {Node<vec3>} The computed normal vector.
  27261. */
  27262. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  27263. const size = textureSize( textureLoad( depthTexture ) );
  27264. const p = ivec2( uv.mul( size ) ).toVar();
  27265. const c0 = textureLoad( depthTexture, p ).toVar();
  27266. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  27267. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  27268. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  27269. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  27270. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  27271. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  27272. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  27273. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  27274. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  27275. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  27276. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  27277. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  27278. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  27279. 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 ) ) );
  27280. 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 ) ) );
  27281. return normalize( cross( dpdx, dpdy ) );
  27282. } );
  27283. /**
  27284. * Interleaved Gradient Noise (IGN) from Jimenez 2014.
  27285. *
  27286. * IGN has "low discrepancy" resulting in evenly distributed samples. It's superior compared to
  27287. * default white noise, blue noise or Bayer.
  27288. *
  27289. * References:
  27290. * - {@link https://www.iryoku.com/next-generation-post-processing-in-call-of-duty-advanced-warfare/}
  27291. * - {@link https://blog.demofox.org/2022/01/01/interleaved-gradient-noise-a-different-kind-of-low-discrepancy-sequence/}
  27292. *
  27293. * @tsl
  27294. * @function
  27295. * @param {Node<vec2>} position - The input position, usually screen coordinates.
  27296. * @return {Node<float>} The noise value.
  27297. */
  27298. const interleavedGradientNoise = Fn( ( [ position ] ) => {
  27299. return fract( float( 52.9829189 ).mul( fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) ) );
  27300. } ).setLayout( {
  27301. name: 'interleavedGradientNoise',
  27302. type: 'float',
  27303. inputs: [
  27304. { name: 'position', type: 'vec2' }
  27305. ]
  27306. } );
  27307. /**
  27308. * Vogel disk sampling for uniform circular distribution.
  27309. *
  27310. * This function generates sample points distributed uniformly on a disk using the golden angle,
  27311. * resulting in an efficient low-discrepancy sequence for sampling. The rotation parameter (phi)
  27312. * allows randomizing the pattern per-pixel when combined with IGN.
  27313. *
  27314. * @tsl
  27315. * @function
  27316. * @param {Node<int>} sampleIndex - The index of the current sample (0-based).
  27317. * @param {Node<int>} samplesCount - The total number of samples.
  27318. * @param {Node<float>} phi - Rotation angle in radians (typically from IGN * 2π).
  27319. * @return {Node<vec2>} A 2D point on the unit disk.
  27320. */
  27321. const vogelDiskSample = Fn( ( [ sampleIndex, samplesCount, phi ] ) => {
  27322. const goldenAngle = float( 2.399963229728653 ); // 2π * (2 - φ) where φ is golden ratio
  27323. const r = sqrt( float( sampleIndex ).add( 0.5 ).div( float( samplesCount ) ) );
  27324. const theta = float( sampleIndex ).mul( goldenAngle ).add( phi );
  27325. return vec2( cos( theta ), sin( theta ) ).mul( r );
  27326. } ).setLayout( {
  27327. name: 'vogelDiskSample',
  27328. type: 'vec2',
  27329. inputs: [
  27330. { name: 'sampleIndex', type: 'int' },
  27331. { name: 'samplesCount', type: 'int' },
  27332. { name: 'phi', type: 'float' }
  27333. ]
  27334. } );
  27335. /**
  27336. * Class representing a node that samples a value using a provided callback function.
  27337. *
  27338. * @extends Node
  27339. */
  27340. class SampleNode extends Node {
  27341. /**
  27342. * Returns the type of the node.
  27343. *
  27344. * @type {string}
  27345. * @readonly
  27346. * @static
  27347. */
  27348. static get type() {
  27349. return 'SampleNode';
  27350. }
  27351. /**
  27352. * Creates an instance of SampleNode.
  27353. *
  27354. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  27355. * @param {?Node<vec2>} [uvNode=null] - The UV node to be used in the texture sampling.
  27356. */
  27357. constructor( callback, uvNode = null ) {
  27358. super();
  27359. this.callback = callback;
  27360. /**
  27361. * Represents the texture coordinates.
  27362. *
  27363. * @type {?Node<vec2|vec3>}
  27364. * @default null
  27365. */
  27366. this.uvNode = uvNode;
  27367. /**
  27368. * This flag can be used for type testing.
  27369. *
  27370. * @type {boolean}
  27371. * @readonly
  27372. * @default true
  27373. */
  27374. this.isSampleNode = true;
  27375. }
  27376. /**
  27377. * Sets up the node by sampling with the default UV accessor.
  27378. *
  27379. * @returns {Node} The result of the callback function when called with the UV node.
  27380. */
  27381. setup() {
  27382. return this.sample( uv$1() );
  27383. }
  27384. /**
  27385. * Calls the callback function with the provided UV node.
  27386. *
  27387. * @param {Node<vec2>} uv - The UV node or value to be passed to the callback.
  27388. * @returns {Node} The result of the callback function.
  27389. */
  27390. sample( uv ) {
  27391. return this.callback( uv );
  27392. }
  27393. }
  27394. /**
  27395. * Helper function to create a SampleNode wrapped as a node object.
  27396. *
  27397. * @function
  27398. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  27399. * @param {?Node<vec2>} [uv=null] - The UV node to be used in the texture sampling.
  27400. * @returns {SampleNode} The created SampleNode instance wrapped as a node object.
  27401. */
  27402. const sample = ( callback, uv = null ) => new SampleNode( callback, nodeObject( uv ) );
  27403. /**
  27404. * This special type of instanced buffer attribute is intended for compute shaders.
  27405. * In earlier three.js versions it was only possible to update attribute data
  27406. * on the CPU via JavaScript and then upload the data to the GPU. With the
  27407. * new material system and renderer it is now possible to use compute shaders
  27408. * to compute the data for an attribute more efficiently on the GPU.
  27409. *
  27410. * The idea is to create an instance of this class and provide it as an input
  27411. * to {@link StorageBufferNode}.
  27412. *
  27413. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  27414. *
  27415. * @augments InstancedBufferAttribute
  27416. */
  27417. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  27418. /**
  27419. * Constructs a new storage instanced buffer attribute.
  27420. *
  27421. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  27422. * The subsequent parameters are then obsolete.
  27423. * @param {number} itemSize - The item size.
  27424. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  27425. */
  27426. constructor( count, itemSize, typeClass = Float32Array ) {
  27427. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  27428. super( array, itemSize );
  27429. /**
  27430. * This flag can be used for type testing.
  27431. *
  27432. * @type {boolean}
  27433. * @readonly
  27434. * @default true
  27435. */
  27436. this.isStorageInstancedBufferAttribute = true;
  27437. }
  27438. }
  27439. /**
  27440. * This special type of buffer attribute is intended for compute shaders.
  27441. * In earlier three.js versions it was only possible to update attribute data
  27442. * on the CPU via JavaScript and then upload the data to the GPU. With the
  27443. * new material system and renderer it is now possible to use compute shaders
  27444. * to compute the data for an attribute more efficiently on the GPU.
  27445. *
  27446. * The idea is to create an instance of this class and provide it as an input
  27447. * to {@link StorageBufferNode}.
  27448. *
  27449. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  27450. *
  27451. * @augments BufferAttribute
  27452. */
  27453. class StorageBufferAttribute extends BufferAttribute {
  27454. /**
  27455. * Constructs a new storage buffer attribute.
  27456. *
  27457. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  27458. * The subsequent parameters are then obsolete.
  27459. * @param {number} itemSize - The item size.
  27460. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  27461. */
  27462. constructor( count, itemSize, typeClass = Float32Array ) {
  27463. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  27464. super( array, itemSize );
  27465. /**
  27466. * This flag can be used for type testing.
  27467. *
  27468. * @type {boolean}
  27469. * @readonly
  27470. * @default true
  27471. */
  27472. this.isStorageBufferAttribute = true;
  27473. }
  27474. }
  27475. /**
  27476. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  27477. *
  27478. * @tsl
  27479. * @function
  27480. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  27481. * @param {string|Struct} [type='float'] - The data type.
  27482. * @returns {StorageBufferNode}
  27483. */
  27484. const attributeArray = ( count, type = 'float' ) => {
  27485. let itemSize, typedArray;
  27486. if ( type.isStructTypeNode === true ) {
  27487. itemSize = type.getLength();
  27488. typedArray = getTypedArrayFromType( 'float' );
  27489. } else {
  27490. itemSize = getLengthFromType( type );
  27491. typedArray = getTypedArrayFromType( type );
  27492. }
  27493. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  27494. const node = storage( buffer, type, count );
  27495. return node;
  27496. };
  27497. /**
  27498. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  27499. *
  27500. * @tsl
  27501. * @function
  27502. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  27503. * @param {string|Struct} [type='float'] - The data type.
  27504. * @returns {StorageBufferNode}
  27505. */
  27506. const instancedArray = ( count, type = 'float' ) => {
  27507. let itemSize, typedArray;
  27508. if ( type.isStructTypeNode === true ) {
  27509. itemSize = type.getLength();
  27510. typedArray = getTypedArrayFromType( 'float' );
  27511. } else {
  27512. itemSize = getLengthFromType( type );
  27513. typedArray = getTypedArrayFromType( type );
  27514. }
  27515. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  27516. const node = storage( buffer, type, buffer.count );
  27517. return node;
  27518. };
  27519. /**
  27520. * A node for representing the uv coordinates of points.
  27521. *
  27522. * Can only be used with a WebGL backend. In WebGPU, point
  27523. * primitives always have the size of one pixel and can thus
  27524. * can't be used as sprite-like objects that display textures.
  27525. *
  27526. * @augments Node
  27527. */
  27528. class PointUVNode extends Node {
  27529. static get type() {
  27530. return 'PointUVNode';
  27531. }
  27532. /**
  27533. * Constructs a new point uv node.
  27534. */
  27535. constructor() {
  27536. super( 'vec2' );
  27537. /**
  27538. * This flag can be used for type testing.
  27539. *
  27540. * @type {boolean}
  27541. * @readonly
  27542. * @default true
  27543. */
  27544. this.isPointUVNode = true;
  27545. }
  27546. generate( /*builder*/ ) {
  27547. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  27548. }
  27549. }
  27550. /**
  27551. * TSL object that represents the uv coordinates of points.
  27552. *
  27553. * @tsl
  27554. * @type {PointUVNode}
  27555. */
  27556. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  27557. const _m1 = /*@__PURE__*/ new Matrix4();
  27558. /**
  27559. * TSL object that represents the scene's background blurriness.
  27560. *
  27561. * @tsl
  27562. * @type {Node<float>}
  27563. */
  27564. const backgroundBlurriness = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( { scene } ) => scene.backgroundBlurriness );
  27565. /**
  27566. * TSL object that represents the scene's background intensity.
  27567. *
  27568. * @tsl
  27569. * @type {Node<float>}
  27570. */
  27571. const backgroundIntensity = /*@__PURE__*/ uniform( 1 ).setGroup( renderGroup ).onRenderUpdate( ( { scene } ) => scene.backgroundIntensity );
  27572. /**
  27573. * TSL object that represents the scene's background rotation.
  27574. *
  27575. * @tsl
  27576. * @type {Node<mat4>}
  27577. */
  27578. const backgroundRotation = /*@__PURE__*/ uniform( new Matrix4() ).setGroup( renderGroup ).onRenderUpdate( ( { scene } ) => {
  27579. const background = scene.background;
  27580. if ( ( background !== null && background.isTexture && background.mapping !== UVMapping ) || ( scene.backgroundNode && scene.backgroundNode.isNode ) ) {
  27581. // note: since the matrix is orthonormal, we can use the more-efficient transpose() in lieu of invert()
  27582. _m1.makeRotationFromEuler( scene.backgroundRotation ).transpose();
  27583. } else {
  27584. _m1.identity();
  27585. }
  27586. return _m1;
  27587. } );
  27588. /**
  27589. * This special version of a texture node can be used to
  27590. * write data into a storage texture with a compute shader.
  27591. *
  27592. * ```js
  27593. * const storageTexture = new THREE.StorageTexture( width, height );
  27594. *
  27595. * const computeTexture = Fn( ( { storageTexture } ) => {
  27596. *
  27597. * const posX = instanceIndex.mod( width );
  27598. * const posY = instanceIndex.div( width );
  27599. * const indexUV = uvec2( posX, posY );
  27600. *
  27601. * // generate RGB values
  27602. *
  27603. * const r = 1;
  27604. * const g = 1;
  27605. * const b = 1;
  27606. *
  27607. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  27608. *
  27609. * } );
  27610. *
  27611. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  27612. * renderer.computeAsync( computeNode );
  27613. * ```
  27614. *
  27615. * This node can only be used with a WebGPU backend.
  27616. *
  27617. * @augments TextureNode
  27618. */
  27619. class StorageTextureNode extends TextureNode {
  27620. static get type() {
  27621. return 'StorageTextureNode';
  27622. }
  27623. /**
  27624. * Constructs a new storage texture node.
  27625. *
  27626. * @param {StorageTexture} value - The storage texture.
  27627. * @param {Node<vec2|vec3>} uvNode - The uv node.
  27628. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  27629. */
  27630. constructor( value, uvNode, storeNode = null ) {
  27631. super( value, uvNode );
  27632. /**
  27633. * The value node that should be stored in the texture.
  27634. *
  27635. * @type {?Node}
  27636. * @default null
  27637. */
  27638. this.storeNode = storeNode;
  27639. /**
  27640. * The mip level to write to for storage textures.
  27641. *
  27642. * @type {number}
  27643. * @default 0
  27644. */
  27645. this.mipLevel = 0;
  27646. /**
  27647. * This flag can be used for type testing.
  27648. *
  27649. * @type {boolean}
  27650. * @readonly
  27651. * @default true
  27652. */
  27653. this.isStorageTextureNode = true;
  27654. /**
  27655. * The access type of the texture node.
  27656. *
  27657. * @type {string}
  27658. * @default 'writeOnly'
  27659. */
  27660. this.access = NodeAccess.WRITE_ONLY;
  27661. }
  27662. /**
  27663. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  27664. *
  27665. * @param {NodeBuilder} builder - The current node builder.
  27666. * @return {string} The input type.
  27667. */
  27668. getInputType( /*builder*/ ) {
  27669. return 'storageTexture';
  27670. }
  27671. /**
  27672. * Overwrites the default implementation since storage texture
  27673. * coordinates are texel coordinates and should not be transformed
  27674. * by the texture uv matrix.
  27675. *
  27676. * @param {Node} uvNode - The uv node.
  27677. * @return {Node} The unmodified uv node.
  27678. */
  27679. getTransformedUV( uvNode ) {
  27680. return uvNode;
  27681. }
  27682. setup( builder ) {
  27683. super.setup( builder );
  27684. const properties = builder.getNodeProperties( this );
  27685. properties.storeNode = this.storeNode;
  27686. return properties;
  27687. }
  27688. /**
  27689. * Defines the node access.
  27690. *
  27691. * @param {string} value - The node access.
  27692. * @return {StorageTextureNode} A reference to this node.
  27693. */
  27694. setAccess( value ) {
  27695. this.access = value;
  27696. return this;
  27697. }
  27698. /**
  27699. * Sets the mip level to write to.
  27700. *
  27701. * @param {number} level - The mip level.
  27702. * @return {StorageTextureNode} A reference to this node.
  27703. */
  27704. setMipLevel( level ) {
  27705. this.mipLevel = level;
  27706. return this;
  27707. }
  27708. /**
  27709. * Generates the code snippet of the storage node. If no `storeNode`
  27710. * is defined, the texture node is generated as normal texture.
  27711. *
  27712. * @param {NodeBuilder} builder - The current node builder.
  27713. * @param {string} output - The current output.
  27714. * @return {string} The generated code snippet.
  27715. */
  27716. generate( builder, output ) {
  27717. if ( this.storeNode !== null ) {
  27718. this.generateStore( builder );
  27719. return '';
  27720. }
  27721. return super.generate( builder, output );
  27722. }
  27723. /**
  27724. * Generates the snippet for the storage texture.
  27725. *
  27726. * @param {NodeBuilder} builder - The current node builder.
  27727. * @param {string} textureProperty - The texture property.
  27728. * @param {string} uvSnippet - The uv snippet.
  27729. * @param {?string} levelSnippet - The level snippet.
  27730. * @param {?string} biasSnippet - The bias snippet.
  27731. * @param {?string} depthSnippet - The depth snippet.
  27732. * @param {?string} compareSnippet - The compare snippet.
  27733. * @param {?Array<string>} gradSnippet - The grad snippet.
  27734. * @param {?string} offsetSnippet - The offset snippet.
  27735. * @return {string} The generated code snippet.
  27736. */
  27737. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet ) {
  27738. const texture = this.value;
  27739. return builder.generateStorageTextureLoad( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  27740. }
  27741. /**
  27742. * Convenience method for configuring a read/write node access.
  27743. *
  27744. * @return {StorageTextureNode} A reference to this node.
  27745. */
  27746. toReadWrite() {
  27747. return this.setAccess( NodeAccess.READ_WRITE );
  27748. }
  27749. /**
  27750. * Convenience method for configuring a read-only node access.
  27751. *
  27752. * @return {StorageTextureNode} A reference to this node.
  27753. */
  27754. toReadOnly() {
  27755. return this.setAccess( NodeAccess.READ_ONLY );
  27756. }
  27757. /**
  27758. * Convenience method for configuring a write-only node access.
  27759. *
  27760. * @return {StorageTextureNode} A reference to this node.
  27761. */
  27762. toWriteOnly() {
  27763. return this.setAccess( NodeAccess.WRITE_ONLY );
  27764. }
  27765. /**
  27766. * Stores a value in this storage texture at the given coordinates.
  27767. *
  27768. * @param {Node<vec2|vec3>} uvNode - The storage texture coordinates.
  27769. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  27770. * @return {StorageTextureNode} A storage texture node representing the store operation.
  27771. */
  27772. store( uvNode, storeNode ) {
  27773. const node = this.clone();
  27774. node.referenceNode = this.getBase();
  27775. node.uvNode = uvNode;
  27776. node.storeNode = storeNode;
  27777. if ( storeNode !== null ) node.toStack();
  27778. return node;
  27779. }
  27780. /**
  27781. * Generates the code snippet of the storage texture node.
  27782. *
  27783. * @param {NodeBuilder} builder - The current node builder.
  27784. */
  27785. generateStore( builder ) {
  27786. const properties = builder.getNodeProperties( this );
  27787. const { uvNode, storeNode, depthNode } = properties;
  27788. const textureProperty = super.generate( builder, 'property' );
  27789. const uvSnippet = uvNode.build( builder, this.value.is3DTexture === true ? 'uvec3' : 'uvec2' );
  27790. const storeSnippet = storeNode.build( builder, 'vec4' );
  27791. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  27792. const snippet = builder.generateTextureStore( this.value, textureProperty, uvSnippet, depthSnippet, storeSnippet );
  27793. builder.addLineFlowCode( snippet, this );
  27794. }
  27795. clone() {
  27796. const newNode = super.clone();
  27797. newNode.storeNode = this.storeNode;
  27798. newNode.mipLevel = this.mipLevel;
  27799. newNode.access = this.access;
  27800. return newNode;
  27801. }
  27802. }
  27803. /**
  27804. * TSL function for creating a storage texture node.
  27805. *
  27806. * @tsl
  27807. * @function
  27808. * @param {StorageTexture} value - The storage texture.
  27809. * @param {?Node<vec2|vec3>} uvNode - The uv node.
  27810. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  27811. * @returns {StorageTextureNode}
  27812. */
  27813. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode ).setParameterLength( 1, 3 );
  27814. /**
  27815. * TODO: Explain difference to `storageTexture()`.
  27816. *
  27817. * @tsl
  27818. * @function
  27819. * @param {StorageTexture|StorageTextureNode} value - The storage texture.
  27820. * @param {Node<vec2|vec3>} uvNode - The uv node.
  27821. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  27822. * @returns {StorageTextureNode}
  27823. */
  27824. const textureStore = ( value, uvNode, storeNode ) => {
  27825. let node;
  27826. if ( value.isStorageTextureNode === true ) {
  27827. node = value.store( uvNode, storeNode );
  27828. } else {
  27829. node = storageTexture( value, uvNode, storeNode );
  27830. if ( storeNode !== null ) node.toStack();
  27831. }
  27832. return node;
  27833. };
  27834. /**
  27835. * This special version of a texture node can be used to
  27836. * write data into a 3D storage texture with a compute shader.
  27837. *
  27838. * @augments StorageTextureNode
  27839. */
  27840. class StorageTexture3DNode extends StorageTextureNode {
  27841. static get type() {
  27842. return 'StorageTexture3DNode';
  27843. }
  27844. /**
  27845. * Constructs a new 3D storage texture node.
  27846. *
  27847. * @param {Storage3DTexture} value - The 3D storage texture.
  27848. * @param {Node<vec3>} uvNode - The uv node.
  27849. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  27850. */
  27851. constructor( value, uvNode, storeNode = null ) {
  27852. super( value, uvNode, storeNode );
  27853. /**
  27854. * This flag can be used for type testing.
  27855. *
  27856. * @type {boolean}
  27857. * @readonly
  27858. * @default true
  27859. */
  27860. this.isStorageTexture3DNode = true;
  27861. }
  27862. /**
  27863. * Returns a default uv node which is in context of 3D textures a three-dimensional
  27864. * uv node.
  27865. *
  27866. * @return {Node<vec3>} The default uv node.
  27867. */
  27868. getDefaultUV() {
  27869. return vec3( 0.5, 0.5, 0.5 );
  27870. }
  27871. /**
  27872. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  27873. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  27874. *
  27875. * @param {boolean} value - The update toggle.
  27876. */
  27877. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  27878. /**
  27879. * Generates the uv code snippet.
  27880. *
  27881. * @param {NodeBuilder} builder - The current node builder.
  27882. * @param {Node} uvNode - The uv node to generate code for.
  27883. * @return {string} The generated code snippet.
  27884. */
  27885. generateUV( builder, uvNode ) {
  27886. return uvNode.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  27887. }
  27888. /**
  27889. * Generates the offset code snippet.
  27890. *
  27891. * @param {NodeBuilder} builder - The current node builder.
  27892. * @param {Node} offsetNode - The offset node to generate code for.
  27893. * @return {string} The generated code snippet.
  27894. */
  27895. generateOffset( builder, offsetNode ) {
  27896. return offsetNode.build( builder, 'ivec3' );
  27897. }
  27898. }
  27899. /**
  27900. * TSL function for creating a 3D storage texture node.
  27901. *
  27902. * @tsl
  27903. * @function
  27904. * @param {Storage3DTexture} value - The 3D storage texture.
  27905. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  27906. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  27907. * @returns {StorageTexture3DNode}
  27908. */
  27909. const storageTexture3D = /*@__PURE__*/ nodeProxy( StorageTexture3DNode ).setParameterLength( 1, 3 );
  27910. const normal = Fn( ( { texture, uv } ) => {
  27911. const epsilon = 0.0001;
  27912. const ret = vec3().toVar();
  27913. If( uv.x.lessThan( epsilon ), () => {
  27914. ret.assign( vec3( 1, 0, 0 ) );
  27915. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  27916. ret.assign( vec3( 0, 1, 0 ) );
  27917. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  27918. ret.assign( vec3( 0, 0, 1 ) );
  27919. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  27920. ret.assign( vec3( -1, 0, 0 ) );
  27921. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  27922. ret.assign( vec3( 0, -1, 0 ) );
  27923. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  27924. ret.assign( vec3( 0, 0, -1 ) );
  27925. } ).Else( () => {
  27926. const step = 0.01;
  27927. const x = texture.sample( uv.add( vec3( - step, 0.0, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( step, 0.0, 0.0 ) ) ).r );
  27928. const y = texture.sample( uv.add( vec3( 0.0, - step, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, step, 0.0 ) ) ).r );
  27929. const z = texture.sample( uv.add( vec3( 0.0, 0.0, - step ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, 0.0, step ) ) ).r );
  27930. ret.assign( vec3( x, y, z ) );
  27931. } );
  27932. return ret.normalize();
  27933. } );
  27934. /**
  27935. * This type of uniform node represents a 3D texture.
  27936. *
  27937. * @augments TextureNode
  27938. */
  27939. class Texture3DNode extends TextureNode {
  27940. static get type() {
  27941. return 'Texture3DNode';
  27942. }
  27943. /**
  27944. * Constructs a new 3D texture node.
  27945. *
  27946. * @param {Data3DTexture} value - The 3D texture.
  27947. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  27948. * @param {?Node<int>} [levelNode=null] - The level node.
  27949. */
  27950. constructor( value, uvNode = null, levelNode = null ) {
  27951. super( value, uvNode, levelNode );
  27952. /**
  27953. * This flag can be used for type testing.
  27954. *
  27955. * @type {boolean}
  27956. * @readonly
  27957. * @default true
  27958. */
  27959. this.isTexture3DNode = true;
  27960. }
  27961. /**
  27962. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  27963. *
  27964. * @param {NodeBuilder} builder - The current node builder.
  27965. * @return {string} The input type.
  27966. */
  27967. getInputType( /*builder*/ ) {
  27968. return 'texture3D';
  27969. }
  27970. /**
  27971. * Returns a default uv node which is in context of 3D textures a three-dimensional
  27972. * uv node.
  27973. *
  27974. * @return {Node<vec3>} The default uv node.
  27975. */
  27976. getDefaultUV() {
  27977. return vec3( 0.5, 0.5, 0.5 );
  27978. }
  27979. /**
  27980. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  27981. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  27982. *
  27983. * @param {boolean} value - The update toggle.
  27984. */
  27985. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  27986. /**
  27987. * Generates the uv code snippet.
  27988. *
  27989. * @param {NodeBuilder} builder - The current node builder.
  27990. * @param {Node} uvNode - The uv node to generate code for.
  27991. * @return {string} The generated code snippet.
  27992. */
  27993. generateUV( builder, uvNode ) {
  27994. return uvNode.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  27995. }
  27996. /**
  27997. * Generates the offset code snippet.
  27998. *
  27999. * @param {NodeBuilder} builder - The current node builder.
  28000. * @param {Node} offsetNode - The offset node to generate code for.
  28001. * @return {string} The generated code snippet.
  28002. */
  28003. generateOffset( builder, offsetNode ) {
  28004. return offsetNode.build( builder, 'ivec3' );
  28005. }
  28006. /**
  28007. * Computes the normal for the given uv. These texture coordiantes represent a
  28008. * position inside the 3D texture. Unlike geometric normals, this normal
  28009. * represents a slope or gradient of scalar data inside the 3D texture.
  28010. *
  28011. * @param {Node<vec3>} uvNode - The uv node that defines a position in the 3D texture.
  28012. * @return {Node<vec3>} The normal representing the slope/gradient in the data.
  28013. */
  28014. normal( uvNode ) {
  28015. return normal( { texture: this, uv: uvNode } );
  28016. }
  28017. }
  28018. /**
  28019. * TSL function for creating a 3D texture node.
  28020. *
  28021. * @tsl
  28022. * @function
  28023. * @param {Data3DTexture} value - The 3D texture.
  28024. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  28025. * @param {?Node<int>} [levelNode=null] - The level node.
  28026. * @returns {Texture3DNode}
  28027. */
  28028. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode ).setParameterLength( 1, 3 );
  28029. /**
  28030. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  28031. *
  28032. * @tsl
  28033. * @function
  28034. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  28035. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  28036. * @param {?Node<int>} [levelNode=null] - The level node.
  28037. * @param {?Node<float>} [biasNode=null] - The bias node.
  28038. * @returns {TextureNode}
  28039. */
  28040. const texture3DLoad = ( ...params ) => texture3D( ...params ).setSampler( false );
  28041. /**
  28042. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  28043. *
  28044. * @tsl
  28045. * @function
  28046. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  28047. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  28048. * @param {?Node<int>} [levelNode=null] - The level node.
  28049. * @returns {TextureNode}
  28050. */
  28051. const texture3DLevel = ( value, uvNode, levelNode ) => texture3D( value, uvNode ).level( levelNode );
  28052. /**
  28053. * A special type of reference node that allows to link values in
  28054. * `userData` fields to node objects.
  28055. * ```js
  28056. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  28057. *
  28058. * const material = new THREE.SpriteNodeMaterial();
  28059. * material.rotationNode = userData( 'rotation', 'float' );
  28060. * ```
  28061. * Since `UserDataNode` is extended from {@link ReferenceNode}, the node value
  28062. * will automatically be updated when the `rotation` user data field changes.
  28063. *
  28064. * @augments ReferenceNode
  28065. */
  28066. class UserDataNode extends ReferenceNode {
  28067. static get type() {
  28068. return 'UserDataNode';
  28069. }
  28070. /**
  28071. * Constructs a new user data node.
  28072. *
  28073. * @param {string} property - The property name that should be referenced by the node.
  28074. * @param {string} inputType - The node data type of the reference.
  28075. * @param {?Object} [userData=null] - A reference to the `userData` object. If not provided, the `userData` property of the 3D object that uses the node material is evaluated.
  28076. */
  28077. constructor( property, inputType, userData = null ) {
  28078. super( property, inputType, userData );
  28079. /**
  28080. * A reference to the `userData` object. If not provided, the `userData`
  28081. * property of the 3D object that uses the node material is evaluated.
  28082. *
  28083. * @type {?Object}
  28084. * @default null
  28085. */
  28086. this.userData = userData;
  28087. }
  28088. /**
  28089. * Overwritten to make sure {@link ReferenceNode#reference} points to the correct
  28090. * `userData` field.
  28091. *
  28092. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  28093. * @return {Object} A reference to the `userData` field.
  28094. */
  28095. updateReference( state ) {
  28096. this.reference = this.userData !== null ? this.userData : state.object.userData;
  28097. return this.reference;
  28098. }
  28099. }
  28100. /**
  28101. * TSL function for creating a user data node.
  28102. *
  28103. * @tsl
  28104. * @function
  28105. * @param {string} name - The property name that should be referenced by the node.
  28106. * @param {string} inputType - The node data type of the reference.
  28107. * @param {?Object} userData - A reference to the `userData` object. If not provided, the `userData` property of the 3D object that uses the node material is evaluated.
  28108. * @returns {UserDataNode}
  28109. */
  28110. const userData = ( name, inputType, userData ) => new UserDataNode( name, inputType, userData );
  28111. const _objectData = new WeakMap();
  28112. /**
  28113. * A node for representing motion or velocity vectors. Foundation
  28114. * for advanced post processing effects like motion blur or TRAA.
  28115. *
  28116. * The node keeps track of the model, view and projection matrices
  28117. * of the previous frame and uses them to compute offsets in NDC space.
  28118. * These offsets represent the final velocity.
  28119. *
  28120. * @augments TempNode
  28121. */
  28122. class VelocityNode extends TempNode {
  28123. static get type() {
  28124. return 'VelocityNode';
  28125. }
  28126. /**
  28127. * Constructs a new vertex color node.
  28128. */
  28129. constructor() {
  28130. super( 'vec2' );
  28131. /**
  28132. * The current projection matrix.
  28133. *
  28134. * @type {?Matrix4}
  28135. * @default null
  28136. */
  28137. this.projectionMatrix = null;
  28138. /**
  28139. * Overwritten since velocity nodes are updated per object.
  28140. *
  28141. * @type {string}
  28142. * @default 'object'
  28143. */
  28144. this.updateType = NodeUpdateType.OBJECT;
  28145. /**
  28146. * Overwritten since velocity nodes save data after the update.
  28147. *
  28148. * @type {string}
  28149. * @default 'object'
  28150. */
  28151. this.updateAfterType = NodeUpdateType.OBJECT;
  28152. /**
  28153. * Uniform node representing the previous model matrix in world space.
  28154. *
  28155. * @type {UniformNode<mat4>}
  28156. * @default null
  28157. */
  28158. this.previousModelWorldMatrix = uniform( new Matrix4() );
  28159. /**
  28160. * Uniform node representing the previous projection matrix.
  28161. *
  28162. * @type {UniformNode<mat4>}
  28163. * @default null
  28164. */
  28165. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  28166. /**
  28167. * Uniform node representing the previous view matrix.
  28168. *
  28169. * @type {UniformNode<mat4>}
  28170. * @default null
  28171. */
  28172. this.previousCameraViewMatrix = uniform( new Matrix4() );
  28173. }
  28174. /**
  28175. * Sets the given projection matrix.
  28176. *
  28177. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  28178. */
  28179. setProjectionMatrix( projectionMatrix ) {
  28180. this.projectionMatrix = projectionMatrix;
  28181. }
  28182. /**
  28183. * Updates velocity specific uniforms.
  28184. *
  28185. * @param {NodeFrame} frame - A reference to the current node frame.
  28186. */
  28187. update( { frameId, camera, object } ) {
  28188. const previousModelMatrix = getPreviousMatrix( object );
  28189. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  28190. //
  28191. const cameraData = getData( camera );
  28192. if ( cameraData.frameId !== frameId ) {
  28193. cameraData.frameId = frameId;
  28194. if ( cameraData.previousProjectionMatrix === undefined ) {
  28195. cameraData.previousProjectionMatrix = new Matrix4();
  28196. cameraData.previousCameraViewMatrix = new Matrix4();
  28197. cameraData.currentProjectionMatrix = new Matrix4();
  28198. cameraData.currentCameraViewMatrix = new Matrix4();
  28199. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  28200. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  28201. } else {
  28202. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  28203. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  28204. }
  28205. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  28206. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  28207. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  28208. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  28209. }
  28210. }
  28211. /**
  28212. * Overwritten to updated velocity specific uniforms.
  28213. *
  28214. * @param {NodeFrame} frame - A reference to the current node frame.
  28215. */
  28216. updateAfter( { object } ) {
  28217. getPreviousMatrix( object ).copy( object.matrixWorld );
  28218. }
  28219. /**
  28220. * Implements the velocity computation based on the previous and current vertex data.
  28221. *
  28222. * @param {NodeBuilder} builder - A reference to the current node builder.
  28223. * @return {Node<vec2>} The motion vector.
  28224. */
  28225. setup( /*builder*/ ) {
  28226. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  28227. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  28228. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  28229. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  28230. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  28231. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  28232. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  28233. return velocity;
  28234. }
  28235. }
  28236. function getData( object ) {
  28237. let objectData = _objectData.get( object );
  28238. if ( objectData === undefined ) {
  28239. objectData = {};
  28240. _objectData.set( object, objectData );
  28241. }
  28242. return objectData;
  28243. }
  28244. function getPreviousMatrix( object, index = 0 ) {
  28245. const objectData = getData( object );
  28246. let matrix = objectData[ index ];
  28247. if ( matrix === undefined ) {
  28248. objectData[ index ] = matrix = new Matrix4();
  28249. objectData[ index ].copy( object.matrixWorld );
  28250. }
  28251. return matrix;
  28252. }
  28253. /**
  28254. * TSL object that represents the velocity of a render pass.
  28255. *
  28256. * @tsl
  28257. * @type {VelocityNode}
  28258. */
  28259. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  28260. /**
  28261. * Represents a "Color Burn" blend mode.
  28262. *
  28263. * It's designed to darken the base layer's colors based on the color of the blend layer.
  28264. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  28265. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  28266. *
  28267. * @tsl
  28268. * @function
  28269. * @param {Node<vec3>} base - The base color.
  28270. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  28271. * @return {Node<vec3>} The result.
  28272. */
  28273. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  28274. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  28275. } ).setLayout( {
  28276. name: 'blendBurn',
  28277. type: 'vec3',
  28278. inputs: [
  28279. { name: 'base', type: 'vec3' },
  28280. { name: 'blend', type: 'vec3' }
  28281. ]
  28282. } );
  28283. /**
  28284. * Represents a "Color Dodge" blend mode.
  28285. *
  28286. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  28287. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  28288. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  28289. *
  28290. * @tsl
  28291. * @function
  28292. * @param {Node<vec3>} base - The base color.
  28293. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  28294. * @return {Node<vec3>} The result.
  28295. */
  28296. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  28297. return min$1( base.div( blend.oneMinus() ), 1.0 );
  28298. } ).setLayout( {
  28299. name: 'blendDodge',
  28300. type: 'vec3',
  28301. inputs: [
  28302. { name: 'base', type: 'vec3' },
  28303. { name: 'blend', type: 'vec3' }
  28304. ]
  28305. } );
  28306. /**
  28307. * Represents a "Screen" blend mode.
  28308. *
  28309. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  28310. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  28311. * effects.
  28312. *
  28313. * @tsl
  28314. * @function
  28315. * @param {Node<vec3>} base - The base color.
  28316. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  28317. * @return {Node<vec3>} The result.
  28318. */
  28319. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  28320. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  28321. } ).setLayout( {
  28322. name: 'blendScreen',
  28323. type: 'vec3',
  28324. inputs: [
  28325. { name: 'base', type: 'vec3' },
  28326. { name: 'blend', type: 'vec3' }
  28327. ]
  28328. } );
  28329. /**
  28330. * Represents a "Overlay" blend mode.
  28331. *
  28332. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  28333. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  28334. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  28335. *
  28336. * @tsl
  28337. * @function
  28338. * @param {Node<vec3>} base - The base color.
  28339. * @param {Node<vec3>} blend - The blend color
  28340. * @return {Node<vec3>} The result.
  28341. */
  28342. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  28343. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  28344. } ).setLayout( {
  28345. name: 'blendOverlay',
  28346. type: 'vec3',
  28347. inputs: [
  28348. { name: 'base', type: 'vec3' },
  28349. { name: 'blend', type: 'vec3' }
  28350. ]
  28351. } );
  28352. /**
  28353. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  28354. * It assumes both input colors have non-premultiplied alpha.
  28355. *
  28356. * @tsl
  28357. * @function
  28358. * @param {Node<vec4>} base - The base color.
  28359. * @param {Node<vec4>} blend - The blend color
  28360. * @return {Node<vec4>} The result.
  28361. */
  28362. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  28363. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  28364. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  28365. } ).setLayout( {
  28366. name: 'blendColor',
  28367. type: 'vec4',
  28368. inputs: [
  28369. { name: 'base', type: 'vec4' },
  28370. { name: 'blend', type: 'vec4' }
  28371. ]
  28372. } );
  28373. /**
  28374. * Computes a grayscale value for the given RGB color value.
  28375. *
  28376. * @tsl
  28377. * @function
  28378. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  28379. * @return {Node<vec3>} The grayscale color.
  28380. */
  28381. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  28382. return luminance( color.rgb );
  28383. } );
  28384. /**
  28385. * Super-saturates or desaturates the given RGB color.
  28386. *
  28387. * @tsl
  28388. * @function
  28389. * @param {Node<vec3>} color - The input color.
  28390. * @param {Node<float>} [adjustment=1] - Specifies the amount of the conversion. A value under `1` desaturates the color, a value over `1` super-saturates it.
  28391. * @return {Node<vec3>} The saturated color.
  28392. */
  28393. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  28394. return adjustment.mix( luminance( color.rgb ), color.rgb ).max( 0.0 );
  28395. } );
  28396. /**
  28397. * Selectively enhance the intensity of less saturated RGB colors. Can result
  28398. * in a more natural and visually appealing image with enhanced color depth
  28399. * compared to {@link ColorAdjustment#saturation}.
  28400. *
  28401. * @tsl
  28402. * @function
  28403. * @param {Node<vec3>} color - The input color.
  28404. * @param {Node<float>} [adjustment=0] - Controls the intensity of the vibrance effect.
  28405. * @return {Node<vec3>} The updated color.
  28406. */
  28407. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 0 ) ] ) => {
  28408. const average = add( color.r, color.g, color.b ).div( 3.0 );
  28409. const mx = color.r.max( color.g.max( color.b ) );
  28410. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  28411. return mix( color.rgb, mx, amt ).max( 0.0 );
  28412. } );
  28413. /**
  28414. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  28415. *
  28416. * @tsl
  28417. * @function
  28418. * @param {Node<vec3>} color - The input color.
  28419. * @param {Node<float>} [adjustment=1] - Defines the degree of hue rotation in radians. A positive value rotates the hue clockwise, while a negative value rotates it counterclockwise.
  28420. * @return {Node<vec3>} The updated color.
  28421. */
  28422. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  28423. const k = vec3( 0.57735, 0.57735, 0.57735 );
  28424. const cosAngle = adjustment.cos();
  28425. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) ).max( 0.0 );
  28426. } );
  28427. /**
  28428. * Computes the luminance for the given RGB color value.
  28429. *
  28430. * @tsl
  28431. * @function
  28432. * @param {Node<vec3>} color - The color value to compute the luminance for.
  28433. * @param {?Node<vec3>} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  28434. * @return {Node<float>} The luminance.
  28435. */
  28436. const luminance = (
  28437. color,
  28438. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  28439. ) => dot( color, luminanceCoefficients );
  28440. /**
  28441. * Color Decision List (CDL) v1.2
  28442. *
  28443. * Compact representation of color grading information, defined by slope, offset, power, and
  28444. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  28445. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  28446. *
  28447. * @tsl
  28448. * @function
  28449. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  28450. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  28451. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  28452. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  28453. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  28454. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  28455. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  28456. *
  28457. * References:
  28458. * - ASC CDL v1.2
  28459. * - {@link https://blender.stackexchange.com/a/55239/43930}
  28460. * - {@link https://docs.acescentral.com/specifications/acescc/}
  28461. */
  28462. const cdl = /*@__PURE__*/ Fn( ( [
  28463. color,
  28464. slope = vec3( 1 ),
  28465. offset = vec3( 0 ),
  28466. power = vec3( 1 ),
  28467. saturation = float( 1 ),
  28468. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  28469. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  28470. ] ) => {
  28471. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  28472. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  28473. // if negative inputs to the power expression are avoided. We use `max( in, 0.0 )`
  28474. // on final output, but the lower limit may not be required in all cases.
  28475. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  28476. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 );
  28477. const pv = v.pow( power );
  28478. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  28479. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  28480. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  28481. v.assign( luma.add( v.sub( luma ).mul( saturation ) ).max( 0 ) );
  28482. return vec4( v.rgb, color.a );
  28483. } );
  28484. /**
  28485. * TSL function for creating a posterize effect which reduces the number of colors
  28486. * in an image, resulting in a more blocky and stylized appearance.
  28487. *
  28488. * @tsl
  28489. * @function
  28490. * @param {Node} sourceNode - The input color.
  28491. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  28492. * @returns {Node} The posterized color.
  28493. */
  28494. const posterize = Fn( ( [ source, steps ] ) => {
  28495. return source.mul( steps ).floor().div( steps );
  28496. } );
  28497. let _sharedFramebuffer = null;
  28498. /**
  28499. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  28500. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  28501. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  28502. *
  28503. * @augments ViewportTextureNode
  28504. */
  28505. class ViewportSharedTextureNode extends ViewportTextureNode {
  28506. static get type() {
  28507. return 'ViewportSharedTextureNode';
  28508. }
  28509. /**
  28510. * Constructs a new viewport shared texture node.
  28511. *
  28512. * @param {Node} [uvNode=screenUV] - The uv node.
  28513. * @param {?Node} [levelNode=null] - The level node.
  28514. */
  28515. constructor( uvNode = screenUV, levelNode = null ) {
  28516. if ( _sharedFramebuffer === null ) {
  28517. _sharedFramebuffer = new FramebufferTexture();
  28518. }
  28519. super( uvNode, levelNode, _sharedFramebuffer );
  28520. }
  28521. /**
  28522. * Overwritten so the method always returns the unique shared
  28523. * framebuffer texture.
  28524. *
  28525. * @return {FramebufferTexture} The shared framebuffer texture.
  28526. */
  28527. getTextureForReference() {
  28528. return _sharedFramebuffer;
  28529. }
  28530. updateReference() {
  28531. return this;
  28532. }
  28533. }
  28534. /**
  28535. * TSL function for creating a shared viewport texture node.
  28536. *
  28537. * @tsl
  28538. * @function
  28539. * @param {?Node} [uvNode=screenUV] - The uv node.
  28540. * @param {?Node} [levelNode=null] - The level node.
  28541. * @returns {ViewportSharedTextureNode}
  28542. */
  28543. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode ).setParameterLength( 0, 2 );
  28544. const _size = /*@__PURE__*/ new Vector2();
  28545. /**
  28546. * Represents the texture of a pass node.
  28547. *
  28548. * @augments TextureNode
  28549. */
  28550. class PassTextureNode extends TextureNode {
  28551. static get type() {
  28552. return 'PassTextureNode';
  28553. }
  28554. /**
  28555. * Constructs a new pass texture node.
  28556. *
  28557. * @param {PassNode} passNode - The pass node.
  28558. * @param {Texture} texture - The output texture.
  28559. */
  28560. constructor( passNode, texture ) {
  28561. super( texture );
  28562. /**
  28563. * A reference to the pass node.
  28564. *
  28565. * @type {PassNode}
  28566. */
  28567. this.passNode = passNode;
  28568. /**
  28569. * This flag can be used for type testing.
  28570. *
  28571. * @type {boolean}
  28572. * @default true
  28573. * @readonly
  28574. */
  28575. this.isPassTextureNode = true;
  28576. this.setUpdateMatrix( false );
  28577. }
  28578. setup( builder ) {
  28579. const properties = builder.getNodeProperties( this );
  28580. properties.passNode = this.passNode;
  28581. return super.setup( builder );
  28582. }
  28583. clone() {
  28584. return new this.constructor( this.passNode, this.value );
  28585. }
  28586. }
  28587. /**
  28588. * An extension of `PassTextureNode` which allows to manage more than one
  28589. * internal texture. Relevant for the `getPreviousTexture()` related API.
  28590. *
  28591. * @augments PassTextureNode
  28592. */
  28593. class PassMultipleTextureNode extends PassTextureNode {
  28594. static get type() {
  28595. return 'PassMultipleTextureNode';
  28596. }
  28597. /**
  28598. * Constructs a new pass texture node.
  28599. *
  28600. * @param {PassNode} passNode - The pass node.
  28601. * @param {string} textureName - The output texture name.
  28602. * @param {boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  28603. */
  28604. constructor( passNode, textureName, previousTexture = false ) {
  28605. // null is passed to the super call since this class does not
  28606. // use an external texture for rendering pass data into. Instead
  28607. // the texture is managed by the pass node itself
  28608. super( passNode, null );
  28609. /**
  28610. * The output texture name.
  28611. *
  28612. * @type {string}
  28613. */
  28614. this.textureName = textureName;
  28615. /**
  28616. * Whether previous frame data should be used or not.
  28617. *
  28618. * @type {boolean}
  28619. */
  28620. this.previousTexture = previousTexture;
  28621. /**
  28622. * This flag can be used for type testing.
  28623. *
  28624. * @type {boolean}
  28625. * @default true
  28626. * @readonly
  28627. */
  28628. this.isPassMultipleTextureNode = true;
  28629. }
  28630. /**
  28631. * Updates the texture reference of this node.
  28632. */
  28633. updateTexture() {
  28634. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  28635. }
  28636. setup( builder ) {
  28637. this.updateTexture();
  28638. return super.setup( builder );
  28639. }
  28640. clone() {
  28641. const newNode = new this.constructor( this.passNode, this.textureName, this.previousTexture );
  28642. newNode.uvNode = this.uvNode;
  28643. newNode.levelNode = this.levelNode;
  28644. newNode.biasNode = this.biasNode;
  28645. newNode.sampler = this.sampler;
  28646. newNode.depthNode = this.depthNode;
  28647. newNode.compareNode = this.compareNode;
  28648. newNode.gradNode = this.gradNode;
  28649. newNode.gatherNode = this.gatherNode;
  28650. newNode.offsetNode = this.offsetNode;
  28651. return newNode;
  28652. }
  28653. }
  28654. /**
  28655. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  28656. * This pass produces a render for the given scene and camera and can provide multiple outputs
  28657. * via MRT for further processing.
  28658. *
  28659. * ```js
  28660. * const postProcessing = new RenderPipeline( renderer );
  28661. *
  28662. * const scenePass = pass( scene, camera );
  28663. *
  28664. * postProcessing.outputNode = scenePass;
  28665. * ```
  28666. *
  28667. * @augments TempNode
  28668. */
  28669. class PassNode extends TempNode {
  28670. static get type() {
  28671. return 'PassNode';
  28672. }
  28673. /**
  28674. * Constructs a new pass node.
  28675. *
  28676. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  28677. * @param {Scene} scene - A reference to the scene.
  28678. * @param {Camera} camera - A reference to the camera.
  28679. * @param {Object} options - Options for the internal render target.
  28680. */
  28681. constructor( scope, scene, camera, options = {} ) {
  28682. super( 'vec4' );
  28683. /**
  28684. * The scope of the pass. The scope determines whether the node outputs color or depth.
  28685. *
  28686. * @type {('color'|'depth')}
  28687. */
  28688. this.scope = scope;
  28689. /**
  28690. * A reference to the scene.
  28691. *
  28692. * @type {Scene}
  28693. */
  28694. this.scene = scene;
  28695. /**
  28696. * A reference to the camera.
  28697. *
  28698. * @type {Camera}
  28699. */
  28700. this.camera = camera;
  28701. /**
  28702. * Options for the internal render target.
  28703. *
  28704. * @type {Object}
  28705. */
  28706. this.options = options;
  28707. /**
  28708. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  28709. * @private
  28710. * @type {number}
  28711. * @default 1
  28712. */
  28713. this._width = 1;
  28714. /**
  28715. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  28716. * @private
  28717. * @type {number}
  28718. * @default 1
  28719. */
  28720. this._height = 1;
  28721. const renderTarget = new RenderTarget( this._width, this._height, { type: HalfFloatType, ...options, } );
  28722. renderTarget.texture.name = 'output';
  28723. let depthTexture = null;
  28724. if ( this.scope === PassNode.DEPTH || options.depthBuffer !== false ) {
  28725. depthTexture = new DepthTexture();
  28726. depthTexture.isRenderTargetTexture = true;
  28727. //depthTexture.type = FloatType;
  28728. depthTexture.name = 'depth';
  28729. renderTarget.depthTexture = depthTexture;
  28730. }
  28731. /**
  28732. * The pass's render target.
  28733. *
  28734. * @type {RenderTarget}
  28735. */
  28736. this.renderTarget = renderTarget;
  28737. /**
  28738. * An optional override material for the pass.
  28739. *
  28740. * @type {Material|null}
  28741. */
  28742. this.overrideMaterial = null;
  28743. /**
  28744. * Whether the pass is transparent.
  28745. *
  28746. * @type {boolean}
  28747. * @default false
  28748. */
  28749. this.transparent = true;
  28750. /**
  28751. * Whether the pass is opaque.
  28752. *
  28753. * @type {boolean}
  28754. * @default true
  28755. */
  28756. this.opaque = true;
  28757. /**
  28758. * An optional global context for the pass.
  28759. *
  28760. * @type {ContextNode|null}
  28761. */
  28762. this.contextNode = null;
  28763. /**
  28764. * A cache for the context node.
  28765. *
  28766. * @private
  28767. * @type {?Object}
  28768. * @default null
  28769. */
  28770. this._contextNodeCache = null;
  28771. /**
  28772. * A dictionary holding the internal result textures.
  28773. *
  28774. * @private
  28775. * @type {{ output: Texture, depth: ?DepthTexture }}
  28776. */
  28777. this._textures = {
  28778. output: renderTarget.texture
  28779. };
  28780. if ( depthTexture !== null ) {
  28781. this._textures.depth = depthTexture;
  28782. }
  28783. /**
  28784. * A dictionary holding the internal texture nodes.
  28785. *
  28786. * @private
  28787. * @type {Object<string, TextureNode>}
  28788. */
  28789. this._textureNodes = {};
  28790. /**
  28791. * A dictionary holding the internal depth nodes.
  28792. *
  28793. * @private
  28794. * @type {Object}
  28795. */
  28796. this._linearDepthNodes = {};
  28797. /**
  28798. * A dictionary holding the internal viewZ nodes.
  28799. *
  28800. * @private
  28801. * @type {Object}
  28802. */
  28803. this._viewZNodes = {};
  28804. /**
  28805. * A dictionary holding the texture data of the previous frame.
  28806. * Used for computing velocity/motion vectors.
  28807. *
  28808. * @private
  28809. * @type {Object<string, Texture>}
  28810. */
  28811. this._previousTextures = {};
  28812. /**
  28813. * A dictionary holding the texture nodes of the previous frame.
  28814. * Used for computing velocity/motion vectors.
  28815. *
  28816. * @private
  28817. * @type {Object<string, TextureNode>}
  28818. */
  28819. this._previousTextureNodes = {};
  28820. /**
  28821. * The `near` property of the camera as a uniform.
  28822. *
  28823. * @private
  28824. * @type {UniformNode}
  28825. */
  28826. this._cameraNear = uniform( 0 );
  28827. /**
  28828. * The `far` property of the camera as a uniform.
  28829. *
  28830. * @private
  28831. * @type {UniformNode}
  28832. */
  28833. this._cameraFar = uniform( 0 );
  28834. /**
  28835. * A MRT node configuring the MRT settings.
  28836. *
  28837. * @private
  28838. * @type {?MRTNode}
  28839. * @default null
  28840. */
  28841. this._mrt = null;
  28842. /**
  28843. * Layer object for configuring the camera that is used
  28844. * to produce the pass.
  28845. *
  28846. * @private
  28847. * @type {?Layers}
  28848. * @default null
  28849. */
  28850. this._layers = null;
  28851. /**
  28852. * Scales the resolution of the internal render target.
  28853. *
  28854. * @private
  28855. * @type {number}
  28856. * @default 1
  28857. */
  28858. this._resolutionScale = 1;
  28859. /**
  28860. * Custom viewport definition.
  28861. *
  28862. * @private
  28863. * @type {?Vector4}
  28864. * @default null
  28865. */
  28866. this._viewport = null;
  28867. /**
  28868. * Custom scissor definition.
  28869. *
  28870. * @private
  28871. * @type {?Vector4}
  28872. * @default null
  28873. */
  28874. this._scissor = null;
  28875. /**
  28876. * This flag can be used for type testing.
  28877. *
  28878. * @type {boolean}
  28879. * @readonly
  28880. * @default true
  28881. */
  28882. this.isPassNode = true;
  28883. /**
  28884. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  28885. * scene once per frame in its {@link PassNode#updateBefore} method.
  28886. *
  28887. * @type {string}
  28888. * @default 'frame'
  28889. */
  28890. this.updateBeforeType = NodeUpdateType.FRAME;
  28891. /**
  28892. * This flag is used for global cache.
  28893. *
  28894. * @type {boolean}
  28895. * @default true
  28896. */
  28897. this.global = true;
  28898. }
  28899. /**
  28900. * Sets the resolution scale for the pass.
  28901. * The resolution scale is a factor that is multiplied with the renderer's width and height.
  28902. *
  28903. * @param {number} resolutionScale - The resolution scale to set. A value of `1` means full resolution.
  28904. * @return {PassNode} A reference to this pass.
  28905. */
  28906. setResolutionScale( resolutionScale ) {
  28907. this._resolutionScale = resolutionScale;
  28908. return this;
  28909. }
  28910. /**
  28911. * Gets the current resolution scale of the pass.
  28912. *
  28913. * @return {number} The current resolution scale. A value of `1` means full resolution.
  28914. */
  28915. getResolutionScale() {
  28916. return this._resolutionScale;
  28917. }
  28918. /**
  28919. * Sets the resolution for the pass.
  28920. * The resolution is a factor that is multiplied with the renderer's width and height.
  28921. *
  28922. * @param {number} resolution - The resolution to set. A value of `1` means full resolution.
  28923. * @return {PassNode} A reference to this pass.
  28924. * @deprecated since r181. Use {@link PassNode#setResolutionScale `setResolutionScale()`} instead.
  28925. */
  28926. setResolution( resolution ) { // @deprecated, r181
  28927. warn( 'PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead.' );
  28928. return this.setResolutionScale( resolution );
  28929. }
  28930. /**
  28931. * Gets the current resolution of the pass.
  28932. *
  28933. * @return {number} The current resolution. A value of `1` means full resolution.
  28934. * @deprecated since r181. Use {@link PassNode#getResolutionScale `getResolutionScale()`} instead.
  28935. */
  28936. getResolution() { // @deprecated, r181
  28937. warn( 'PassNode: .getResolution() is deprecated. Use .getResolutionScale() instead.' );
  28938. return this.getResolutionScale();
  28939. }
  28940. /**
  28941. * Sets the layer configuration that should be used when rendering the pass.
  28942. *
  28943. * @param {Layers} layers - The layers object to set.
  28944. * @return {PassNode} A reference to this pass.
  28945. */
  28946. setLayers( layers ) {
  28947. this._layers = layers;
  28948. return this;
  28949. }
  28950. /**
  28951. * Gets the current layer configuration of the pass.
  28952. *
  28953. * @return {?Layers} .
  28954. */
  28955. getLayers() {
  28956. return this._layers;
  28957. }
  28958. /**
  28959. * Sets the given MRT node to setup MRT for this pass.
  28960. *
  28961. * @param {MRTNode} mrt - The MRT object.
  28962. * @return {PassNode} A reference to this pass.
  28963. */
  28964. setMRT( mrt ) {
  28965. this._mrt = mrt;
  28966. return this;
  28967. }
  28968. /**
  28969. * Returns the current MRT node.
  28970. *
  28971. * @return {MRTNode} The current MRT node.
  28972. */
  28973. getMRT() {
  28974. return this._mrt;
  28975. }
  28976. /**
  28977. * Returns the texture for the given output name.
  28978. *
  28979. * @param {string} name - The output name to get the texture for.
  28980. * @return {Texture} The texture.
  28981. */
  28982. getTexture( name ) {
  28983. let texture = this._textures[ name ];
  28984. if ( texture === undefined ) {
  28985. if ( name === 'depth' ) {
  28986. throw new Error( 'THREE.PassNode: Depth texture is not available for this pass.' );
  28987. }
  28988. const refTexture = this.renderTarget.texture;
  28989. texture = refTexture.clone();
  28990. texture.name = name;
  28991. this._textures[ name ] = texture;
  28992. this.renderTarget.textures.push( texture );
  28993. }
  28994. return texture;
  28995. }
  28996. /**
  28997. * Returns the texture holding the data of the previous frame for the given output name.
  28998. *
  28999. * @param {string} name - The output name to get the texture for.
  29000. * @return {Texture} The texture holding the data of the previous frame.
  29001. */
  29002. getPreviousTexture( name ) {
  29003. let texture = this._previousTextures[ name ];
  29004. if ( texture === undefined ) {
  29005. texture = this.getTexture( name ).clone();
  29006. this._previousTextures[ name ] = texture;
  29007. }
  29008. return texture;
  29009. }
  29010. /**
  29011. * Switches current and previous textures for the given output name.
  29012. *
  29013. * @param {string} name - The output name.
  29014. */
  29015. toggleTexture( name ) {
  29016. const prevTexture = this._previousTextures[ name ];
  29017. if ( prevTexture !== undefined ) {
  29018. const texture = this._textures[ name ];
  29019. const index = this.renderTarget.textures.indexOf( texture );
  29020. this.renderTarget.textures[ index ] = prevTexture;
  29021. this._textures[ name ] = prevTexture;
  29022. this._previousTextures[ name ] = texture;
  29023. this._textureNodes[ name ].updateTexture();
  29024. this._previousTextureNodes[ name ].updateTexture();
  29025. }
  29026. }
  29027. /**
  29028. * Returns the texture node for the given output name.
  29029. *
  29030. * @param {string} [name='output'] - The output name to get the texture node for.
  29031. * @return {TextureNode} The texture node.
  29032. */
  29033. getTextureNode( name = 'output' ) {
  29034. let textureNode = this._textureNodes[ name ];
  29035. if ( textureNode === undefined ) {
  29036. textureNode = new PassMultipleTextureNode( this, name );
  29037. textureNode.updateTexture();
  29038. this._textureNodes[ name ] = textureNode;
  29039. }
  29040. return textureNode;
  29041. }
  29042. /**
  29043. * Returns the previous texture node for the given output name.
  29044. *
  29045. * @param {string} [name='output'] - The output name to get the previous texture node for.
  29046. * @return {TextureNode} The previous texture node.
  29047. */
  29048. getPreviousTextureNode( name = 'output' ) {
  29049. let textureNode = this._previousTextureNodes[ name ];
  29050. if ( textureNode === undefined ) {
  29051. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  29052. textureNode = new PassMultipleTextureNode( this, name, true );
  29053. textureNode.updateTexture();
  29054. this._previousTextureNodes[ name ] = textureNode;
  29055. }
  29056. return textureNode;
  29057. }
  29058. /**
  29059. * Returns a viewZ node of this pass.
  29060. *
  29061. * @param {string} [name='depth'] - The output name to get the viewZ node for. In most cases the default `'depth'` can be used however the parameter exists for custom depth outputs.
  29062. * @return {Node} The viewZ node.
  29063. */
  29064. getViewZNode( name = 'depth' ) {
  29065. let viewZNode = this._viewZNodes[ name ];
  29066. if ( viewZNode === undefined ) {
  29067. const cameraNear = this._cameraNear;
  29068. const cameraFar = this._cameraFar;
  29069. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  29070. }
  29071. return viewZNode;
  29072. }
  29073. /**
  29074. * Returns a linear depth node of this pass.
  29075. *
  29076. * @param {string} [name='depth'] - The output name to get the linear depth node for. In most cases the default `'depth'` can be used however the parameter exists for custom depth outputs.
  29077. * @return {Node} The linear depth node.
  29078. */
  29079. getLinearDepthNode( name = 'depth' ) {
  29080. let linearDepthNode = this._linearDepthNodes[ name ];
  29081. if ( linearDepthNode === undefined ) {
  29082. const cameraNear = this._cameraNear;
  29083. const cameraFar = this._cameraFar;
  29084. const viewZNode = this.getViewZNode( name );
  29085. // TODO: just if ( builder.camera.isPerspectiveCamera )
  29086. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  29087. }
  29088. return linearDepthNode;
  29089. }
  29090. /**
  29091. * Precompiles the pass.
  29092. *
  29093. * Note that this method must be called after the pass configuration is complete.
  29094. * So calls like `setMRT()` and `getTextureNode()` must proceed the precompilation.
  29095. *
  29096. * @async
  29097. * @param {Renderer} renderer - The renderer.
  29098. * @return {Promise} A Promise that resolves when the compile has been finished.
  29099. * @see {@link Renderer#compileAsync}
  29100. */
  29101. async compileAsync( renderer ) {
  29102. const currentRenderTarget = renderer.getRenderTarget();
  29103. const currentMRT = renderer.getMRT();
  29104. renderer.setRenderTarget( this.renderTarget );
  29105. renderer.setMRT( this._mrt );
  29106. await renderer.compileAsync( this.scene, this.camera );
  29107. renderer.setRenderTarget( currentRenderTarget );
  29108. renderer.setMRT( currentMRT );
  29109. }
  29110. setup( { renderer } ) {
  29111. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  29112. this.renderTarget.texture.type = renderer.getOutputBufferType();
  29113. if ( renderer.reversedDepthBuffer === true && this.renderTarget.depthTexture !== null ) {
  29114. this.renderTarget.depthTexture.type = FloatType;
  29115. }
  29116. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  29117. }
  29118. updateBefore( frame ) {
  29119. const { renderer } = frame;
  29120. const { scene } = this;
  29121. let camera;
  29122. const outputRenderTarget = renderer.getOutputRenderTarget();
  29123. if ( outputRenderTarget && outputRenderTarget.isXRRenderTarget === true ) {
  29124. camera = renderer.xr.getCamera();
  29125. renderer.xr.updateCamera( camera );
  29126. _size.set( outputRenderTarget.width, outputRenderTarget.height );
  29127. } else {
  29128. camera = this.camera;
  29129. renderer.getDrawingBufferSize( _size );
  29130. }
  29131. this.setSize( _size.width, _size.height );
  29132. const currentRenderTarget = renderer.getRenderTarget();
  29133. const currentMRT = renderer.getMRT();
  29134. const currentAutoClear = renderer.autoClear;
  29135. const currentTransparent = renderer.transparent;
  29136. const currentOpaque = renderer.opaque;
  29137. const currentMask = camera.layers.mask;
  29138. const currentContextNode = renderer.contextNode;
  29139. const currentOverrideMaterial = scene.overrideMaterial;
  29140. this._cameraNear.value = camera.near;
  29141. this._cameraFar.value = camera.far;
  29142. if ( this._layers !== null ) {
  29143. camera.layers.mask = this._layers.mask;
  29144. }
  29145. for ( const name in this._previousTextures ) {
  29146. this.toggleTexture( name );
  29147. }
  29148. if ( this.overrideMaterial !== null ) {
  29149. scene.overrideMaterial = this.overrideMaterial;
  29150. }
  29151. renderer.setRenderTarget( this.renderTarget );
  29152. renderer.setMRT( this._mrt );
  29153. renderer.autoClear = true;
  29154. renderer.transparent = this.transparent;
  29155. renderer.opaque = this.opaque;
  29156. if ( this.contextNode !== null ) {
  29157. if ( this._contextNodeCache === null || this._contextNodeCache.version !== this.version ) {
  29158. this._contextNodeCache = {
  29159. version: this.version,
  29160. context: context( { ...renderer.contextNode.getFlowContextData(), ...this.contextNode.getFlowContextData() } )
  29161. };
  29162. }
  29163. renderer.contextNode = this._contextNodeCache.context;
  29164. }
  29165. const currentSceneName = scene.name;
  29166. scene.name = this.name ? this.name : scene.name;
  29167. renderer.render( scene, camera );
  29168. scene.name = currentSceneName;
  29169. scene.overrideMaterial = currentOverrideMaterial;
  29170. renderer.setRenderTarget( currentRenderTarget );
  29171. renderer.setMRT( currentMRT );
  29172. renderer.autoClear = currentAutoClear;
  29173. renderer.transparent = currentTransparent;
  29174. renderer.opaque = currentOpaque;
  29175. renderer.contextNode = currentContextNode;
  29176. camera.layers.mask = currentMask;
  29177. }
  29178. /**
  29179. * Sets the size of the pass's render target. Honors the pixel ratio.
  29180. *
  29181. * @param {number} width - The width to set.
  29182. * @param {number} height - The height to set.
  29183. */
  29184. setSize( width, height ) {
  29185. this._width = width;
  29186. this._height = height;
  29187. const effectiveWidth = Math.floor( this._width * this._resolutionScale );
  29188. const effectiveHeight = Math.floor( this._height * this._resolutionScale );
  29189. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  29190. // scissor
  29191. if ( this._scissor !== null ) {
  29192. this.renderTarget.scissor.copy( this._scissor ).multiplyScalar( this._resolutionScale ).floor();
  29193. this.renderTarget.scissorTest = true;
  29194. } else {
  29195. this.renderTarget.scissorTest = false;
  29196. }
  29197. // viewport
  29198. if ( this._viewport !== null ) {
  29199. this.renderTarget.viewport.copy( this._viewport ).multiplyScalar( this._resolutionScale ).floor();
  29200. }
  29201. }
  29202. /**
  29203. * This method allows to define the pass's scissor rectangle. By default, the scissor rectangle is kept
  29204. * in sync with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  29205. * with `null` as the single argument.
  29206. *
  29207. * @param {?(number | Vector4)} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  29208. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  29209. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  29210. * @param {number} width - The width of the scissor box in logical pixel unit.
  29211. * @param {number} height - The height of the scissor box in logical pixel unit.
  29212. */
  29213. setScissor( x, y, width, height ) {
  29214. if ( x === null ) {
  29215. this._scissor = null;
  29216. } else {
  29217. if ( this._scissor === null ) this._scissor = new Vector4();
  29218. if ( x.isVector4 ) {
  29219. this._scissor.copy( x );
  29220. } else {
  29221. this._scissor.set( x, y, width, height );
  29222. }
  29223. }
  29224. }
  29225. /**
  29226. * This method allows to define the pass's viewport. By default, the viewport is kept in sync
  29227. * with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  29228. * with `null` as the single argument.
  29229. *
  29230. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  29231. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  29232. * @param {number} width - The width of the viewport in logical pixel unit.
  29233. * @param {number} height - The height of the viewport in logical pixel unit.
  29234. */
  29235. setViewport( x, y, width, height ) {
  29236. if ( x === null ) {
  29237. this._viewport = null;
  29238. } else {
  29239. if ( this._viewport === null ) this._viewport = new Vector4();
  29240. if ( x.isVector4 ) {
  29241. this._viewport.copy( x );
  29242. } else {
  29243. this._viewport.set( x, y, width, height );
  29244. }
  29245. }
  29246. }
  29247. /**
  29248. * Frees internal resources. Should be called when the node is no longer in use.
  29249. */
  29250. dispose() {
  29251. this.renderTarget.dispose();
  29252. }
  29253. }
  29254. /**
  29255. * @static
  29256. * @type {'color'}
  29257. * @default 'color'
  29258. */
  29259. PassNode.COLOR = 'color';
  29260. /**
  29261. * @static
  29262. * @type {'depth'}
  29263. * @default 'depth'
  29264. */
  29265. PassNode.DEPTH = 'depth';
  29266. /**
  29267. * TSL function for creating a pass node.
  29268. *
  29269. * @tsl
  29270. * @function
  29271. * @param {Scene} scene - A reference to the scene.
  29272. * @param {Camera} camera - A reference to the camera.
  29273. * @param {Object} options - Options for the internal render target.
  29274. * @returns {PassNode}
  29275. */
  29276. const pass = ( scene, camera, options ) => new PassNode( PassNode.COLOR, scene, camera, options );
  29277. /**
  29278. * TSL function for creating a pass texture node.
  29279. *
  29280. * @tsl
  29281. * @function
  29282. * @param {PassNode} pass - The pass node.
  29283. * @param {Texture} texture - The output texture.
  29284. * @returns {PassTextureNode}
  29285. */
  29286. const passTexture = ( pass, texture ) => new PassTextureNode( pass, texture );
  29287. /**
  29288. * TSL function for creating a depth pass node.
  29289. *
  29290. * @tsl
  29291. * @function
  29292. * @param {Scene} scene - A reference to the scene.
  29293. * @param {Camera} camera - A reference to the camera.
  29294. * @param {Object} options - Options for the internal render target.
  29295. * @returns {PassNode}
  29296. */
  29297. const depthPass = ( scene, camera, options ) => new PassNode( PassNode.DEPTH, scene, camera, options );
  29298. /**
  29299. * Represents a render pass for producing a toon outline effect on compatible objects.
  29300. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  29301. * will receive the outline.
  29302. *
  29303. * ```js
  29304. * const postProcessing = new RenderPipeline( renderer );
  29305. *
  29306. * const scenePass = toonOutlinePass( scene, camera );
  29307. *
  29308. * postProcessing.outputNode = scenePass;
  29309. * ```
  29310. * @augments PassNode
  29311. */
  29312. class ToonOutlinePassNode extends PassNode {
  29313. static get type() {
  29314. return 'ToonOutlinePassNode';
  29315. }
  29316. /**
  29317. * Constructs a new outline pass node.
  29318. *
  29319. * @param {Scene} scene - A reference to the scene.
  29320. * @param {Camera} camera - A reference to the camera.
  29321. * @param {Node} colorNode - Defines the outline's color.
  29322. * @param {Node} thicknessNode - Defines the outline's thickness.
  29323. * @param {Node} alphaNode - Defines the outline's alpha.
  29324. */
  29325. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  29326. super( PassNode.COLOR, scene, camera );
  29327. /**
  29328. * Defines the outline's color.
  29329. *
  29330. * @type {Node}
  29331. */
  29332. this.colorNode = colorNode;
  29333. /**
  29334. * Defines the outline's thickness.
  29335. *
  29336. * @type {Node}
  29337. */
  29338. this.thicknessNode = thicknessNode;
  29339. /**
  29340. * Defines the outline's alpha.
  29341. *
  29342. * @type {Node}
  29343. */
  29344. this.alphaNode = alphaNode;
  29345. /**
  29346. * An internal material cache.
  29347. *
  29348. * @private
  29349. * @type {WeakMap<Material, NodeMaterial>}
  29350. */
  29351. this._materialCache = new WeakMap();
  29352. /**
  29353. * The name of this pass.
  29354. *
  29355. * @type {string}
  29356. * @default 'Outline Pass'
  29357. */
  29358. this.name = 'Outline Pass';
  29359. }
  29360. updateBefore( frame ) {
  29361. const { renderer } = frame;
  29362. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  29363. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  29364. // only render outline for supported materials
  29365. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  29366. if ( material.wireframe === false ) {
  29367. const outlineMaterial = this._getOutlineMaterial( material );
  29368. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  29369. }
  29370. }
  29371. // default
  29372. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  29373. } );
  29374. super.updateBefore( frame );
  29375. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  29376. }
  29377. /**
  29378. * Creates the material used for outline rendering.
  29379. *
  29380. * @private
  29381. * @return {NodeMaterial} The outline material.
  29382. */
  29383. _createMaterial() {
  29384. const material = new NodeMaterial();
  29385. material.isMeshToonOutlineMaterial = true;
  29386. material.name = 'Toon_Outline';
  29387. material.side = BackSide;
  29388. // vertex node
  29389. const outlineNormal = normalLocal.negate();
  29390. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  29391. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  29392. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  29393. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  29394. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  29395. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  29396. // color node
  29397. material.colorNode = vec4( this.colorNode, this.alphaNode );
  29398. return material;
  29399. }
  29400. /**
  29401. * For the given toon material, this method returns a corresponding
  29402. * outline material.
  29403. *
  29404. * @private
  29405. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  29406. * @return {NodeMaterial} The outline material.
  29407. */
  29408. _getOutlineMaterial( originalMaterial ) {
  29409. let outlineMaterial = this._materialCache.get( originalMaterial );
  29410. if ( outlineMaterial === undefined ) {
  29411. outlineMaterial = this._createMaterial();
  29412. this._materialCache.set( originalMaterial, outlineMaterial );
  29413. }
  29414. return outlineMaterial;
  29415. }
  29416. }
  29417. /**
  29418. * TSL function for creating a toon outline pass node.
  29419. *
  29420. * @tsl
  29421. * @function
  29422. * @param {Scene} scene - A reference to the scene.
  29423. * @param {Camera} camera - A reference to the camera.
  29424. * @param {Color} color - Defines the outline's color.
  29425. * @param {number} [thickness=0.003] - Defines the outline's thickness.
  29426. * @param {number} [alpha=1] - Defines the outline's alpha.
  29427. * @returns {ToonOutlinePassNode}
  29428. */
  29429. const toonOutlinePass = ( scene, camera, color = new Color( 0, 0, 0 ), thickness = 0.003, alpha = 1 ) => new ToonOutlinePassNode( scene, camera, nodeObject( color ), nodeObject( thickness ), nodeObject( alpha ) );
  29430. /**
  29431. * Linear tone mapping, exposure only.
  29432. *
  29433. * @tsl
  29434. * @function
  29435. * @param {Node<vec3>} color - The color that should be tone mapped.
  29436. * @param {Node<float>} exposure - The exposure.
  29437. * @return {Node<vec3>} The tone mapped color.
  29438. */
  29439. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  29440. return color.mul( exposure ).clamp();
  29441. } ).setLayout( {
  29442. name: 'linearToneMapping',
  29443. type: 'vec3',
  29444. inputs: [
  29445. { name: 'color', type: 'vec3' },
  29446. { name: 'exposure', type: 'float' }
  29447. ]
  29448. } );
  29449. /**
  29450. * Reinhard tone mapping.
  29451. *
  29452. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  29453. *
  29454. * @tsl
  29455. * @function
  29456. * @param {Node<vec3>} color - The color that should be tone mapped.
  29457. * @param {Node<float>} exposure - The exposure.
  29458. * @return {Node<vec3>} The tone mapped color.
  29459. */
  29460. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  29461. color = color.mul( exposure );
  29462. return color.div( color.add( 1.0 ) ).clamp();
  29463. } ).setLayout( {
  29464. name: 'reinhardToneMapping',
  29465. type: 'vec3',
  29466. inputs: [
  29467. { name: 'color', type: 'vec3' },
  29468. { name: 'exposure', type: 'float' }
  29469. ]
  29470. } );
  29471. /**
  29472. * Cineon tone mapping.
  29473. *
  29474. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  29475. *
  29476. * @tsl
  29477. * @function
  29478. * @param {Node<vec3>} color - The color that should be tone mapped.
  29479. * @param {Node<float>} exposure - The exposure.
  29480. * @return {Node<vec3>} The tone mapped color.
  29481. */
  29482. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  29483. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  29484. color = color.mul( exposure );
  29485. color = color.sub( 0.004 ).max( 0.0 );
  29486. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  29487. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  29488. return a.div( b ).pow( 2.2 );
  29489. } ).setLayout( {
  29490. name: 'cineonToneMapping',
  29491. type: 'vec3',
  29492. inputs: [
  29493. { name: 'color', type: 'vec3' },
  29494. { name: 'exposure', type: 'float' }
  29495. ]
  29496. } );
  29497. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  29498. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  29499. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  29500. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  29501. return a.div( b );
  29502. } );
  29503. /**
  29504. * ACESFilmic tone mapping.
  29505. *
  29506. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  29507. *
  29508. * @tsl
  29509. * @function
  29510. * @param {Node<vec3>} color - The color that should be tone mapped.
  29511. * @param {Node<float>} exposure - The exposure.
  29512. * @return {Node<vec3>} The tone mapped color.
  29513. */
  29514. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  29515. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  29516. const ACESInputMat = mat3(
  29517. 0.59719, 0.35458, 0.04823,
  29518. 0.07600, 0.90834, 0.01566,
  29519. 0.02840, 0.13383, 0.83777
  29520. );
  29521. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  29522. const ACESOutputMat = mat3(
  29523. 1.60475, -0.53108, -0.07367,
  29524. -0.10208, 1.10813, -605e-5,
  29525. -327e-5, -0.07276, 1.07602
  29526. );
  29527. color = color.mul( exposure ).div( 0.6 );
  29528. color = ACESInputMat.mul( color );
  29529. // Apply RRT and ODT
  29530. color = RRTAndODTFit( color );
  29531. color = ACESOutputMat.mul( color );
  29532. // Clamp to [0, 1]
  29533. return color.clamp();
  29534. } ).setLayout( {
  29535. name: 'acesFilmicToneMapping',
  29536. type: 'vec3',
  29537. inputs: [
  29538. { name: 'color', type: 'vec3' },
  29539. { name: 'exposure', type: 'float' }
  29540. ]
  29541. } );
  29542. 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, -83e-4, 1.1187 ) );
  29543. 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 ) );
  29544. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  29545. const x = vec3( x_immutable ).toVar();
  29546. const x2 = vec3( x.mul( x ) ).toVar();
  29547. const x4 = vec3( x2.mul( x2 ) ).toVar();
  29548. 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 ) ) ) );
  29549. } );
  29550. /**
  29551. * AgX tone mapping.
  29552. *
  29553. * @tsl
  29554. * @function
  29555. * @param {Node<vec3>} color - The color that should be tone mapped.
  29556. * @param {Node<float>} exposure - The exposure.
  29557. * @return {Node<vec3>} The tone mapped color.
  29558. */
  29559. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  29560. const colortone = vec3( color ).toVar();
  29561. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  29562. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  29563. const AgxMinEv = float( -12.47393 );
  29564. const AgxMaxEv = float( 4.026069 );
  29565. colortone.mulAssign( exposure );
  29566. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  29567. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  29568. colortone.assign( max$1( colortone, 1e-10 ) );
  29569. colortone.assign( log2( colortone ) );
  29570. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  29571. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  29572. colortone.assign( agxDefaultContrastApprox( colortone ) );
  29573. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  29574. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  29575. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  29576. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  29577. return colortone;
  29578. } ).setLayout( {
  29579. name: 'agxToneMapping',
  29580. type: 'vec3',
  29581. inputs: [
  29582. { name: 'color', type: 'vec3' },
  29583. { name: 'exposure', type: 'float' }
  29584. ]
  29585. } );
  29586. /**
  29587. * Neutral tone mapping.
  29588. *
  29589. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  29590. *
  29591. * @tsl
  29592. * @function
  29593. * @param {Node<vec3>} color - The color that should be tone mapped.
  29594. * @param {Node<float>} exposure - The exposure.
  29595. * @return {Node<vec3>} The tone mapped color.
  29596. */
  29597. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  29598. const StartCompression = float( 0.8 - 0.04 );
  29599. const Desaturation = float( 0.15 );
  29600. color = color.mul( exposure );
  29601. const x = min$1( color.r, min$1( color.g, color.b ) );
  29602. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  29603. color.subAssign( offset );
  29604. const peak = max$1( color.r, max$1( color.g, color.b ) );
  29605. If( peak.lessThan( StartCompression ), () => {
  29606. return color;
  29607. } );
  29608. const d = sub( 1, StartCompression );
  29609. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  29610. color.mulAssign( newPeak.div( peak ) );
  29611. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  29612. return mix( color, vec3( newPeak ), g );
  29613. } ).setLayout( {
  29614. name: 'neutralToneMapping',
  29615. type: 'vec3',
  29616. inputs: [
  29617. { name: 'color', type: 'vec3' },
  29618. { name: 'exposure', type: 'float' }
  29619. ]
  29620. } );
  29621. /**
  29622. * This class represents native code sections. It is the base
  29623. * class for modules like {@link FunctionNode} which allows to implement
  29624. * functions with native shader languages.
  29625. *
  29626. * @augments Node
  29627. */
  29628. class CodeNode extends Node {
  29629. static get type() {
  29630. return 'CodeNode';
  29631. }
  29632. /**
  29633. * Constructs a new code node.
  29634. *
  29635. * @param {string} [code=''] - The native code.
  29636. * @param {Array<Node>} [includes=[]] - An array of includes.
  29637. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  29638. */
  29639. constructor( code = '', includes = [], language = '' ) {
  29640. super( 'code' );
  29641. /**
  29642. * This flag can be used for type testing.
  29643. *
  29644. * @type {boolean}
  29645. * @readonly
  29646. * @default true
  29647. */
  29648. this.isCodeNode = true;
  29649. /**
  29650. * This flag is used for global cache.
  29651. *
  29652. * @type {boolean}
  29653. * @default true
  29654. */
  29655. this.global = true;
  29656. /**
  29657. * The native code.
  29658. *
  29659. * @type {string}
  29660. * @default ''
  29661. */
  29662. this.code = code;
  29663. /**
  29664. * An array of includes
  29665. *
  29666. * @type {Array<Node>}
  29667. * @default []
  29668. */
  29669. this.includes = includes;
  29670. /**
  29671. * The used language.
  29672. *
  29673. * @type {('js'|'wgsl'|'glsl')}
  29674. * @default ''
  29675. */
  29676. this.language = language;
  29677. }
  29678. /**
  29679. * Sets the includes of this code node.
  29680. *
  29681. * @param {Array<Node>} includes - The includes to set.
  29682. * @return {CodeNode} A reference to this node.
  29683. */
  29684. setIncludes( includes ) {
  29685. this.includes = includes;
  29686. return this;
  29687. }
  29688. /**
  29689. * Returns the includes of this code node.
  29690. *
  29691. * @param {NodeBuilder} builder - The current node builder.
  29692. * @return {Array<Node>} The includes.
  29693. */
  29694. getIncludes( /*builder*/ ) {
  29695. return this.includes;
  29696. }
  29697. generate( builder ) {
  29698. const includes = this.getIncludes( builder );
  29699. for ( const include of includes ) {
  29700. include.build( builder );
  29701. }
  29702. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  29703. nodeCode.code = this.code;
  29704. return nodeCode.code;
  29705. }
  29706. serialize( data ) {
  29707. super.serialize( data );
  29708. data.code = this.code;
  29709. data.language = this.language;
  29710. }
  29711. deserialize( data ) {
  29712. super.deserialize( data );
  29713. this.code = data.code;
  29714. this.language = data.language;
  29715. }
  29716. }
  29717. /**
  29718. * TSL function for creating a code node.
  29719. *
  29720. * @tsl
  29721. * @function
  29722. * @param {string} [code] - The native code.
  29723. * @param {?Array<Node>} [includes=[]] - An array of includes.
  29724. * @param {?('js'|'wgsl'|'glsl')} [language=''] - The used language.
  29725. * @returns {CodeNode}
  29726. */
  29727. const code = /*@__PURE__*/ nodeProxy( CodeNode ).setParameterLength( 1, 3 );
  29728. /**
  29729. * TSL function for creating a JS code node.
  29730. *
  29731. * @tsl
  29732. * @function
  29733. * @param {string} src - The native code.
  29734. * @param {Array<Node>} includes - An array of includes.
  29735. * @returns {CodeNode}
  29736. */
  29737. const js = ( src, includes ) => code( src, includes, 'js' );
  29738. /**
  29739. * TSL function for creating a WGSL code node.
  29740. *
  29741. * @tsl
  29742. * @function
  29743. * @param {string} src - The native code.
  29744. * @param {Array<Node>} includes - An array of includes.
  29745. * @returns {CodeNode}
  29746. */
  29747. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  29748. /**
  29749. * TSL function for creating a GLSL code node.
  29750. *
  29751. * @tsl
  29752. * @function
  29753. * @param {string} src - The native code.
  29754. * @param {Array<Node>} includes - An array of includes.
  29755. * @returns {CodeNode}
  29756. */
  29757. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  29758. /**
  29759. * This class represents a native shader function. It can be used to implement
  29760. * certain aspects of a node material with native shader code. There are two predefined
  29761. * TSL functions for easier usage.
  29762. *
  29763. * - `wgslFn`: Creates a WGSL function node.
  29764. * - `glslFn`: Creates a GLSL function node.
  29765. *
  29766. * A basic example with one include looks like so:
  29767. *
  29768. * ```js
  29769. * const desaturateWGSLFn = wgslFn( `
  29770. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  29771. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  29772. * return vec3<f32>( dot( lum, color ) );
  29773. * }`
  29774. *);
  29775. * const someWGSLFn = wgslFn( `
  29776. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  29777. * return desaturate( color );
  29778. * }
  29779. * `, [ desaturateWGSLFn ] );
  29780. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  29781. *```
  29782. * @augments CodeNode
  29783. */
  29784. class FunctionNode extends CodeNode {
  29785. static get type() {
  29786. return 'FunctionNode';
  29787. }
  29788. /**
  29789. * Constructs a new function node.
  29790. *
  29791. * @param {string} [code=''] - The native code.
  29792. * @param {Array<Node>} [includes=[]] - An array of includes.
  29793. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  29794. */
  29795. constructor( code = '', includes = [], language = '' ) {
  29796. super( code, includes, language );
  29797. }
  29798. /**
  29799. * Returns the type of this function node.
  29800. *
  29801. * @param {NodeBuilder} builder - The current node builder.
  29802. * @return {string} The type.
  29803. */
  29804. generateNodeType( builder ) {
  29805. return this.getNodeFunction( builder ).type;
  29806. }
  29807. /**
  29808. * Returns the type of a member of this function node.
  29809. *
  29810. * @param {NodeBuilder} builder - The current node builder.
  29811. * @param {string} name - The name of the member.
  29812. * @return {string} The type of the member.
  29813. */
  29814. getMemberType( builder, name ) {
  29815. const type = this.getNodeType( builder );
  29816. const structType = builder.getStructTypeNode( type );
  29817. return structType.getMemberType( builder, name );
  29818. }
  29819. /**
  29820. * Returns the inputs of this function node.
  29821. *
  29822. * @param {NodeBuilder} builder - The current node builder.
  29823. * @return {Array<NodeFunctionInput>} The inputs.
  29824. */
  29825. getInputs( builder ) {
  29826. return this.getNodeFunction( builder ).inputs;
  29827. }
  29828. /**
  29829. * Returns the node function for this function node.
  29830. *
  29831. * @param {NodeBuilder} builder - The current node builder.
  29832. * @return {NodeFunction} The node function.
  29833. */
  29834. getNodeFunction( builder ) {
  29835. const nodeData = builder.getDataFromNode( this );
  29836. let nodeFunction = nodeData.nodeFunction;
  29837. if ( nodeFunction === undefined ) {
  29838. nodeFunction = builder.parser.parseFunction( this.code );
  29839. nodeData.nodeFunction = nodeFunction;
  29840. }
  29841. return nodeFunction;
  29842. }
  29843. generate( builder, output ) {
  29844. super.generate( builder );
  29845. const nodeFunction = this.getNodeFunction( builder );
  29846. const name = nodeFunction.name;
  29847. const type = nodeFunction.type;
  29848. const nodeCode = builder.getCodeFromNode( this, type );
  29849. if ( name !== '' ) {
  29850. const nodeData = builder.getDataFromNode( this );
  29851. if ( nodeData.declarationRegistered !== true ) {
  29852. // use a custom property name
  29853. nodeCode.name = name;
  29854. builder.registerDeclaration( nodeCode );
  29855. nodeData.declarationRegistered = true;
  29856. }
  29857. }
  29858. const propertyName = builder.getPropertyName( nodeCode );
  29859. const code = this.getNodeFunction( builder ).getCode( propertyName );
  29860. nodeCode.code = code + '\n';
  29861. if ( output === 'property' ) {
  29862. return propertyName;
  29863. } else {
  29864. return builder.format( `${ propertyName }()`, type, output );
  29865. }
  29866. }
  29867. }
  29868. const nativeFn = ( code, includes = [], language = '' ) => {
  29869. const functionNode = new FunctionNode( code, includes, language );
  29870. const fn = ( ...params ) => functionNode.call( ...params );
  29871. return nodeProxyConstructor( fn, functionNode );
  29872. };
  29873. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  29874. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  29875. /**
  29876. * Returns a node that represents the `z` coordinate in view space
  29877. * for the current fragment. It's a different representation of the
  29878. * default depth value.
  29879. *
  29880. * This value can be part of a computation that defines how the fog
  29881. * density increases when moving away from the camera.
  29882. *
  29883. * @param {NodeBuilder} builder - The current node builder.
  29884. * @return {Node} The viewZ node.
  29885. */
  29886. function getViewZNode( builder ) {
  29887. let viewZ;
  29888. const getViewZ = builder.context.getViewZ;
  29889. if ( getViewZ !== undefined ) {
  29890. viewZ = getViewZ( this );
  29891. }
  29892. return ( viewZ || positionView.z ).negate();
  29893. }
  29894. /**
  29895. * Constructs a new range factor node.
  29896. *
  29897. * @tsl
  29898. * @function
  29899. * @param {Node} near - Defines the near value.
  29900. * @param {Node} far - Defines the far value.
  29901. */
  29902. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  29903. const viewZ = getViewZNode( builder );
  29904. return smoothstep( near, far, viewZ );
  29905. } );
  29906. /**
  29907. * Represents an exponential squared fog. This type of fog gives
  29908. * a clear view near the camera and a faster than exponentially
  29909. * densening fog farther from the camera.
  29910. *
  29911. * @tsl
  29912. * @function
  29913. * @param {Node} density - Defines the fog density.
  29914. */
  29915. const densityFogFactor = Fn( ( [ density ], builder ) => {
  29916. const viewZ = getViewZNode( builder );
  29917. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  29918. } );
  29919. /**
  29920. * Constructs a new height fog factor node. This fog factor requires a Y-up coordinate system.
  29921. *
  29922. * @tsl
  29923. * @function
  29924. * @param {Node} density - Defines the fog density.
  29925. * @param {Node} height - The height threshold in world space. Everything below this y-coordinate is affected by fog.
  29926. */
  29927. const exponentialHeightFogFactor = Fn( ( [ density, height ], builder ) => {
  29928. const viewZ = getViewZNode( builder );
  29929. const distance = height.sub( positionWorld.y ).max( 0 ).toConst();
  29930. const m = distance.mul( viewZ ).toConst();
  29931. return density.mul( density, m, m ).negate().exp().oneMinus();
  29932. } );
  29933. /**
  29934. * This class can be used to configure a fog for the scene.
  29935. * Nodes of this type are assigned to `Scene.fogNode`.
  29936. *
  29937. * @tsl
  29938. * @function
  29939. * @param {Node} color - Defines the color of the fog.
  29940. * @param {Node} factor - Defines how the fog is factored in the scene.
  29941. */
  29942. const fog = Fn( ( [ color, factor ] ) => {
  29943. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  29944. } );
  29945. let min = null;
  29946. let max = null;
  29947. /**
  29948. * `RangeNode` generates random instanced attribute data in a defined range.
  29949. * An exemplary use case for this utility node is to generate random per-instance
  29950. * colors:
  29951. * ```js
  29952. * const material = new MeshBasicNodeMaterial();
  29953. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  29954. * const mesh = new InstancedMesh( geometry, material, count );
  29955. * ```
  29956. * @augments Node
  29957. */
  29958. class RangeNode extends Node {
  29959. static get type() {
  29960. return 'RangeNode';
  29961. }
  29962. /**
  29963. * Constructs a new range node.
  29964. *
  29965. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  29966. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  29967. */
  29968. constructor( minNode = float(), maxNode = float() ) {
  29969. super();
  29970. /**
  29971. * A node defining the lower bound of the range.
  29972. *
  29973. * @type {Node<any>}
  29974. * @default float()
  29975. */
  29976. this.minNode = minNode;
  29977. /**
  29978. * A node defining the upper bound of the range.
  29979. *
  29980. * @type {Node<any>}
  29981. * @default float()
  29982. */
  29983. this.maxNode = maxNode;
  29984. }
  29985. /**
  29986. * Returns the vector length which is computed based on the range definition.
  29987. *
  29988. * @param {NodeBuilder} builder - The current node builder.
  29989. * @return {number} The vector length.
  29990. */
  29991. getVectorLength( builder ) {
  29992. const minNode = this.getConstNode( this.minNode );
  29993. const maxNode = this.getConstNode( this.maxNode );
  29994. const minLength = builder.getTypeLength( getValueType( minNode.value ) );
  29995. const maxLength = builder.getTypeLength( getValueType( maxNode.value ) );
  29996. return minLength > maxLength ? minLength : maxLength;
  29997. }
  29998. /**
  29999. * This method is overwritten since the node type is inferred from range definition.
  30000. *
  30001. * @param {NodeBuilder} builder - The current node builder.
  30002. * @return {string} The node type.
  30003. */
  30004. generateNodeType( builder ) {
  30005. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  30006. }
  30007. /**
  30008. * Returns a constant node from the given node by traversing it.
  30009. *
  30010. * @param {Node} node - The node to traverse.
  30011. * @returns {Node} The constant node, if found.
  30012. */
  30013. getConstNode( node ) {
  30014. let output = null;
  30015. node.traverse( n => {
  30016. if ( n.isConstNode === true ) {
  30017. output = n;
  30018. }
  30019. } );
  30020. if ( output === null ) {
  30021. throw new NodeError( 'THREE.TSL: No "ConstNode" found in node graph.', this.stackTrace );
  30022. }
  30023. return output;
  30024. }
  30025. setup( builder ) {
  30026. const object = builder.object;
  30027. let output = null;
  30028. if ( object.count > 1 ) {
  30029. const minNode = this.getConstNode( this.minNode );
  30030. const maxNode = this.getConstNode( this.maxNode );
  30031. const minValue = minNode.value;
  30032. const maxValue = maxNode.value;
  30033. const minLength = builder.getTypeLength( getValueType( minValue ) );
  30034. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  30035. min = min || new Vector4();
  30036. max = max || new Vector4();
  30037. min.setScalar( 0 );
  30038. max.setScalar( 0 );
  30039. if ( minLength === 1 ) min.setScalar( minValue );
  30040. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  30041. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  30042. if ( maxLength === 1 ) max.setScalar( maxValue );
  30043. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  30044. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  30045. const stride = 4;
  30046. const length = stride * object.count;
  30047. const array = new Float32Array( length );
  30048. for ( let i = 0; i < length; i ++ ) {
  30049. const index = i % stride;
  30050. const minElementValue = min.getComponent( index );
  30051. const maxElementValue = max.getComponent( index );
  30052. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  30053. }
  30054. const nodeType = this.getNodeType( builder );
  30055. const uniformBufferSize = object.count * 4 * 4; // count * 4 components * 4 bytes (float)
  30056. if ( uniformBufferSize <= builder.getUniformBufferLimit() ) {
  30057. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  30058. } else {
  30059. // TODO: Improve anonymous buffer attribute creation removing this part
  30060. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  30061. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  30062. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  30063. }
  30064. } else {
  30065. output = float( 0 );
  30066. }
  30067. return output;
  30068. }
  30069. }
  30070. /**
  30071. * TSL function for creating a range node.
  30072. *
  30073. * @tsl
  30074. * @function
  30075. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  30076. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  30077. * @returns {RangeNode}
  30078. */
  30079. const range = /*@__PURE__*/ nodeProxy( RangeNode ).setParameterLength( 2 );
  30080. /**
  30081. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  30082. * about the currently running dispatch and/or the device it is running on.
  30083. *
  30084. * This node can only be used with a WebGPU backend.
  30085. *
  30086. * @augments Node
  30087. */
  30088. class ComputeBuiltinNode extends Node {
  30089. static get type() {
  30090. return 'ComputeBuiltinNode';
  30091. }
  30092. /**
  30093. * Constructs a new compute builtin node.
  30094. *
  30095. * @param {string} builtinName - The built-in name.
  30096. * @param {string} nodeType - The node type.
  30097. */
  30098. constructor( builtinName, nodeType ) {
  30099. super( nodeType );
  30100. /**
  30101. * The built-in name.
  30102. *
  30103. * @private
  30104. * @type {string}
  30105. */
  30106. this._builtinName = builtinName;
  30107. }
  30108. /**
  30109. * This method is overwritten since hash is derived from the built-in name.
  30110. *
  30111. * @param {NodeBuilder} builder - The current node builder.
  30112. * @return {string} The hash.
  30113. */
  30114. getHash( builder ) {
  30115. return this.getBuiltinName( builder );
  30116. }
  30117. /**
  30118. * This method is overwritten since the node type is simply derived from `nodeType`..
  30119. *
  30120. * @param {NodeBuilder} builder - The current node builder.
  30121. * @return {string} The node type.
  30122. */
  30123. generateNodeType( /*builder*/ ) {
  30124. return this.nodeType;
  30125. }
  30126. /**
  30127. * Sets the builtin name.
  30128. *
  30129. * @param {string} builtinName - The built-in name.
  30130. * @return {ComputeBuiltinNode} A reference to this node.
  30131. */
  30132. setBuiltinName( builtinName ) {
  30133. this._builtinName = builtinName;
  30134. return this;
  30135. }
  30136. /**
  30137. * Returns the builtin name.
  30138. *
  30139. * @param {NodeBuilder} builder - The current node builder.
  30140. * @return {string} The builtin name.
  30141. */
  30142. getBuiltinName( /*builder*/ ) {
  30143. return this._builtinName;
  30144. }
  30145. /**
  30146. * Whether the current node builder has the builtin or not.
  30147. *
  30148. * @param {NodeBuilder} builder - The current node builder.
  30149. * @return {boolean} Whether the builder has the builtin or not.
  30150. */
  30151. hasBuiltin( builder ) {
  30152. return builder.hasBuiltin( this._builtinName );
  30153. }
  30154. generate( builder, output ) {
  30155. const builtinName = this.getBuiltinName( builder );
  30156. const nodeType = this.getNodeType( builder );
  30157. if ( builder.shaderStage === 'compute' ) {
  30158. return builder.format( builtinName, nodeType, output );
  30159. } else {
  30160. warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  30161. return builder.generateConst( nodeType );
  30162. }
  30163. }
  30164. serialize( data ) {
  30165. super.serialize( data );
  30166. data.global = this.global;
  30167. data._builtinName = this._builtinName;
  30168. }
  30169. deserialize( data ) {
  30170. super.deserialize( data );
  30171. this.global = data.global;
  30172. this._builtinName = data._builtinName;
  30173. }
  30174. }
  30175. /**
  30176. * TSL function for creating a compute builtin node.
  30177. *
  30178. * @tsl
  30179. * @function
  30180. * @param {string} name - The built-in name.
  30181. * @param {string} nodeType - The node type.
  30182. * @returns {ComputeBuiltinNode}
  30183. */
  30184. const computeBuiltin = ( name, nodeType ) => new ComputeBuiltinNode( name, nodeType );
  30185. /**
  30186. * Represents the number of workgroups dispatched by the compute shader.
  30187. * ```js
  30188. * // Run 512 invocations/threads with a workgroup size of 128.
  30189. * const computeFn = Fn(() => {
  30190. *
  30191. * // numWorkgroups.x = 4
  30192. * storageBuffer.element(0).assign(numWorkgroups.x)
  30193. *
  30194. * })().compute(512, [128]);
  30195. *
  30196. * // Run 512 invocations/threads with the default workgroup size of 64.
  30197. * const computeFn = Fn(() => {
  30198. *
  30199. * // numWorkgroups.x = 8
  30200. * storageBuffer.element(0).assign(numWorkgroups.x)
  30201. *
  30202. * })().compute(512);
  30203. * ```
  30204. *
  30205. * @tsl
  30206. * @type {ComputeBuiltinNode<uvec3>}
  30207. */
  30208. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  30209. /**
  30210. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  30211. * ```js
  30212. * // Execute 12 compute threads with a workgroup size of 3.
  30213. * const computeFn = Fn( () => {
  30214. *
  30215. * If( workgroupId.x.mod( 2 ).equal( 0 ), () => {
  30216. *
  30217. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  30218. *
  30219. * } ).Else( () => {
  30220. *
  30221. * storageBuffer.element( instanceIndex ).assign( 0 );
  30222. *
  30223. * } );
  30224. *
  30225. * } )().compute( 12, [ 3 ] );
  30226. *
  30227. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  30228. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  30229. * ```
  30230. *
  30231. * @tsl
  30232. * @type {ComputeBuiltinNode<uvec3>}
  30233. */
  30234. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  30235. /**
  30236. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D global grid.
  30237. *
  30238. * @tsl
  30239. * @type {ComputeBuiltinNode<uvec3>}
  30240. */
  30241. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  30242. /**
  30243. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D workgroup grid.
  30244. *
  30245. * @tsl
  30246. * @type {ComputeBuiltinNode<uvec3>}
  30247. */
  30248. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  30249. /**
  30250. * A device dependent variable that exposes the size of the current invocation's subgroup.
  30251. *
  30252. * @tsl
  30253. * @type {ComputeBuiltinNode<uint>}
  30254. */
  30255. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  30256. /**
  30257. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  30258. *
  30259. * This node can only be used with a WebGPU backend.
  30260. *
  30261. * @augments Node
  30262. */
  30263. class BarrierNode extends Node {
  30264. /**
  30265. * Constructs a new barrier node.
  30266. *
  30267. * @param {string} scope - The scope defines the behavior of the node.
  30268. */
  30269. constructor( scope ) {
  30270. super();
  30271. this.scope = scope;
  30272. this.isBarrierNode = true;
  30273. }
  30274. setup( builder ) {
  30275. builder.allowEarlyReturns = false;
  30276. builder.allowGlobalVariables = false;
  30277. }
  30278. generate( builder ) {
  30279. const { scope } = this;
  30280. const { renderer } = builder;
  30281. if ( renderer.backend.isWebGLBackend === true ) {
  30282. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  30283. } else {
  30284. builder.addLineFlowCode( `${scope}Barrier()`, this );
  30285. }
  30286. }
  30287. }
  30288. /**
  30289. * TSL function for creating a barrier node.
  30290. *
  30291. * @tsl
  30292. * @function
  30293. * @param {string} scope - The scope defines the behavior of the node..
  30294. * @returns {BarrierNode}
  30295. */
  30296. const barrier = nodeProxy( BarrierNode );
  30297. /**
  30298. * TSL function for creating a workgroup barrier. All compute shader
  30299. * invocations must wait for each invocation within a workgroup to
  30300. * complete before the barrier can be surpassed.
  30301. *
  30302. * @tsl
  30303. * @function
  30304. * @returns {BarrierNode}
  30305. */
  30306. const workgroupBarrier = () => barrier( 'workgroup' ).toStack();
  30307. /**
  30308. * TSL function for creating a storage barrier. All invocations must
  30309. * wait for each access to variables within the 'storage' address space
  30310. * to complete before the barrier can be passed.
  30311. *
  30312. * @tsl
  30313. * @function
  30314. * @returns {BarrierNode}
  30315. */
  30316. const storageBarrier = () => barrier( 'storage' ).toStack();
  30317. /**
  30318. * TSL function for creating a texture barrier. All invocations must
  30319. * wait for each access to variables within the 'texture' address space
  30320. * to complete before the barrier can be passed.
  30321. *
  30322. * @tsl
  30323. * @function
  30324. * @returns {BarrierNode}
  30325. */
  30326. const textureBarrier = () => barrier( 'texture' ).toStack();
  30327. /**
  30328. * Represents an element of a 'workgroup' scoped buffer.
  30329. *
  30330. * @augments ArrayElementNode
  30331. */
  30332. class WorkgroupInfoElementNode extends ArrayElementNode {
  30333. /**
  30334. * Constructs a new workgroup info element node.
  30335. *
  30336. * @param {Node} workgroupInfoNode - The workgroup info node.
  30337. * @param {Node} indexNode - The index node that defines the element access.
  30338. */
  30339. constructor( workgroupInfoNode, indexNode ) {
  30340. super( workgroupInfoNode, indexNode );
  30341. /**
  30342. * This flag can be used for type testing.
  30343. *
  30344. * @type {boolean}
  30345. * @readonly
  30346. * @default true
  30347. */
  30348. this.isWorkgroupInfoElementNode = true;
  30349. }
  30350. generate( builder, output ) {
  30351. let snippet;
  30352. const isAssignContext = builder.isContextAssign();
  30353. snippet = super.generate( builder );
  30354. if ( isAssignContext !== true ) {
  30355. const type = this.getNodeType( builder );
  30356. snippet = builder.format( snippet, type, output );
  30357. }
  30358. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  30359. return snippet;
  30360. }
  30361. }
  30362. /**
  30363. * A node allowing the user to create a 'workgroup' scoped buffer within the
  30364. * context of a compute shader. Typically, workgroup scoped buffers are
  30365. * created to hold data that is transferred from a global storage scope into
  30366. * a local workgroup scope. For invocations within a workgroup, data
  30367. * access speeds on 'workgroup' scoped buffers can be significantly faster
  30368. * than similar access operations on globally accessible storage buffers.
  30369. *
  30370. * This node can only be used with a WebGPU backend.
  30371. *
  30372. * @augments Node
  30373. */
  30374. class WorkgroupInfoNode extends Node {
  30375. /**
  30376. * Constructs a new buffer scoped to type scope.
  30377. *
  30378. * @param {string} scope - TODO.
  30379. * @param {string} bufferType - The data type of a 'workgroup' scoped buffer element.
  30380. * @param {number} [bufferCount=0] - The number of elements in the buffer.
  30381. */
  30382. constructor( scope, bufferType, bufferCount = 0 ) {
  30383. super( bufferType );
  30384. /**
  30385. * The buffer type.
  30386. *
  30387. * @type {string}
  30388. */
  30389. this.bufferType = bufferType;
  30390. /**
  30391. * The buffer count.
  30392. *
  30393. * @type {number}
  30394. * @default 0
  30395. */
  30396. this.bufferCount = bufferCount;
  30397. /**
  30398. * This flag can be used for type testing.
  30399. *
  30400. * @type {boolean}
  30401. * @readonly
  30402. * @default true
  30403. */
  30404. this.isWorkgroupInfoNode = true;
  30405. /**
  30406. * The data type of the array buffer.
  30407. *
  30408. * @type {string}
  30409. */
  30410. this.elementType = bufferType;
  30411. /**
  30412. * TODO.
  30413. *
  30414. * @type {string}
  30415. */
  30416. this.scope = scope;
  30417. /**
  30418. * The name of the workgroup scoped buffer.
  30419. *
  30420. * @type {string}
  30421. * @default ''
  30422. */
  30423. this.name = '';
  30424. }
  30425. /**
  30426. * Sets the name of this node.
  30427. *
  30428. * @param {string} name - The name to set.
  30429. * @return {WorkgroupInfoNode} A reference to this node.
  30430. */
  30431. setName( name ) {
  30432. this.name = name;
  30433. return this;
  30434. }
  30435. /**
  30436. * Sets the name/label of this node.
  30437. *
  30438. * @deprecated
  30439. * @param {string} name - The name to set.
  30440. * @return {WorkgroupInfoNode} A reference to this node.
  30441. */
  30442. label( name ) {
  30443. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.', new StackTrace() ); // @deprecated r179
  30444. return this.setName( name );
  30445. }
  30446. /**
  30447. * Sets the scope of this node.
  30448. *
  30449. * @param {string} scope - The scope to set.
  30450. * @return {WorkgroupInfoNode} A reference to this node.
  30451. */
  30452. setScope( scope ) {
  30453. this.scope = scope;
  30454. return this;
  30455. }
  30456. /**
  30457. * The data type of the array buffer.
  30458. *
  30459. * @return {string} The element type.
  30460. */
  30461. getElementType() {
  30462. return this.elementType;
  30463. }
  30464. /**
  30465. * Overwrites the default implementation since the input type
  30466. * is inferred from the scope.
  30467. *
  30468. * @param {NodeBuilder} builder - The current node builder.
  30469. * @return {string} The input type.
  30470. */
  30471. getInputType( /*builder*/ ) {
  30472. return `${this.scope}Array`;
  30473. }
  30474. /**
  30475. * This method can be used to access elements via an index node.
  30476. *
  30477. * @param {IndexNode} indexNode - indexNode.
  30478. * @return {WorkgroupInfoElementNode} A reference to an element.
  30479. */
  30480. element( indexNode ) {
  30481. return new WorkgroupInfoElementNode( this, indexNode );
  30482. }
  30483. generate( builder ) {
  30484. const name = ( this.name !== '' ) ? this.name : `${this.scope}Array_${this.id}`;
  30485. return builder.getScopedArray( name, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  30486. }
  30487. }
  30488. /**
  30489. * TSL function for creating a workgroup info node.
  30490. * Creates a new 'workgroup' scoped array buffer.
  30491. *
  30492. * @tsl
  30493. * @function
  30494. * @param {string} type - The data type of a 'workgroup' scoped buffer element.
  30495. * @param {number} [count=0] - The number of elements in the buffer.
  30496. * @returns {WorkgroupInfoNode}
  30497. */
  30498. const workgroupArray = ( type, count ) => new WorkgroupInfoNode( 'Workgroup', type, count );
  30499. /**
  30500. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  30501. * within a shader. In an atomic function, any modification to an atomic variable will
  30502. * occur as an indivisible step with a defined order relative to other modifications.
  30503. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  30504. * atomic operations will not interfere with each other.
  30505. *
  30506. * This node can only be used with a WebGPU backend.
  30507. *
  30508. * @augments Node
  30509. */
  30510. class AtomicFunctionNode extends Node {
  30511. static get type() {
  30512. return 'AtomicFunctionNode';
  30513. }
  30514. /**
  30515. * Constructs a new atomic function node.
  30516. *
  30517. * @param {string} method - The signature of the atomic function to construct.
  30518. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30519. * @param {Node} valueNode - The value that mutates the atomic variable.
  30520. */
  30521. constructor( method, pointerNode, valueNode ) {
  30522. super( 'uint' );
  30523. /**
  30524. * The signature of the atomic function to construct.
  30525. *
  30526. * @type {string}
  30527. */
  30528. this.method = method;
  30529. /**
  30530. * An atomic variable or element of an atomic buffer.
  30531. *
  30532. * @type {Node}
  30533. */
  30534. this.pointerNode = pointerNode;
  30535. /**
  30536. * A value that modifies the atomic variable.
  30537. *
  30538. * @type {Node}
  30539. */
  30540. this.valueNode = valueNode;
  30541. /**
  30542. * Creates a list of the parents for this node for detecting if the node needs to return a value.
  30543. *
  30544. * @type {boolean}
  30545. * @default true
  30546. */
  30547. this.parents = true;
  30548. }
  30549. /**
  30550. * Overwrites the default implementation to return the type of
  30551. * the pointer node.
  30552. *
  30553. * @param {NodeBuilder} builder - The current node builder.
  30554. * @return {string} The input type.
  30555. */
  30556. getInputType( builder ) {
  30557. return this.pointerNode.getNodeType( builder );
  30558. }
  30559. /**
  30560. * Overwritten since the node type is inferred from the input type.
  30561. *
  30562. * @param {NodeBuilder} builder - The current node builder.
  30563. * @return {string} The node type.
  30564. */
  30565. generateNodeType( builder ) {
  30566. return this.getInputType( builder );
  30567. }
  30568. generate( builder ) {
  30569. const properties = builder.getNodeProperties( this );
  30570. const parents = properties.parents;
  30571. const method = this.method;
  30572. const type = this.getNodeType( builder );
  30573. const inputType = this.getInputType( builder );
  30574. const a = this.pointerNode;
  30575. const b = this.valueNode;
  30576. const params = [];
  30577. params.push( `&${ a.build( builder, inputType ) }` );
  30578. if ( b !== null ) {
  30579. params.push( b.build( builder, inputType ) );
  30580. }
  30581. const methodSnippet = `${ builder.getMethod( method, type ) }( ${ params.join( ', ' ) } )`;
  30582. const isVoid = parents ? ( parents.length === 1 && parents[ 0 ].isStackNode === true ) : false;
  30583. if ( isVoid ) {
  30584. builder.addLineFlowCode( methodSnippet, this );
  30585. } else {
  30586. if ( properties.constNode === undefined ) {
  30587. properties.constNode = expression( methodSnippet, type ).toConst();
  30588. }
  30589. return properties.constNode.build( builder );
  30590. }
  30591. }
  30592. }
  30593. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  30594. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  30595. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  30596. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  30597. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  30598. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  30599. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  30600. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  30601. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  30602. /**
  30603. * TSL function for creating an atomic function node.
  30604. *
  30605. * @tsl
  30606. * @function
  30607. * @param {string} method - The signature of the atomic function to construct.
  30608. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30609. * @param {Node} valueNode - The value that mutates the atomic variable.
  30610. * @returns {AtomicFunctionNode}
  30611. */
  30612. const atomicNode = nodeProxy( AtomicFunctionNode );
  30613. /**
  30614. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  30615. *
  30616. * @tsl
  30617. * @function
  30618. * @param {string} method - The signature of the atomic function to construct.
  30619. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30620. * @param {Node} valueNode - The value that mutates the atomic variable.
  30621. * @returns {AtomicFunctionNode}
  30622. */
  30623. const atomicFunc = ( method, pointerNode, valueNode ) => {
  30624. return atomicNode( method, pointerNode, valueNode ).toStack();
  30625. };
  30626. /**
  30627. * Loads the value stored in the atomic variable.
  30628. *
  30629. * @tsl
  30630. * @function
  30631. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30632. * @returns {AtomicFunctionNode}
  30633. */
  30634. const atomicLoad = ( pointerNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null );
  30635. /**
  30636. * Stores a value in the atomic variable.
  30637. *
  30638. * @tsl
  30639. * @function
  30640. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30641. * @param {Node} valueNode - The value that mutates the atomic variable.
  30642. * @returns {AtomicFunctionNode}
  30643. */
  30644. const atomicStore = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode );
  30645. /**
  30646. * Increments the value stored in the atomic variable.
  30647. *
  30648. * @tsl
  30649. * @function
  30650. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30651. * @param {Node} valueNode - The value that mutates the atomic variable.
  30652. * @returns {AtomicFunctionNode}
  30653. */
  30654. const atomicAdd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode );
  30655. /**
  30656. * Decrements the value stored in the atomic variable.
  30657. *
  30658. * @tsl
  30659. * @function
  30660. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30661. * @param {Node} valueNode - The value that mutates the atomic variable.
  30662. * @returns {AtomicFunctionNode}
  30663. */
  30664. const atomicSub = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode );
  30665. /**
  30666. * Stores in an atomic variable the maximum between its current value and a parameter.
  30667. *
  30668. * @tsl
  30669. * @function
  30670. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30671. * @param {Node} valueNode - The value that mutates the atomic variable.
  30672. * @returns {AtomicFunctionNode}
  30673. */
  30674. const atomicMax = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode );
  30675. /**
  30676. * Stores in an atomic variable the minimum between its current value and a parameter.
  30677. *
  30678. * @tsl
  30679. * @function
  30680. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30681. * @param {Node} valueNode - The value that mutates the atomic variable.
  30682. * @returns {AtomicFunctionNode}
  30683. */
  30684. const atomicMin = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode );
  30685. /**
  30686. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  30687. *
  30688. * @tsl
  30689. * @function
  30690. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30691. * @param {Node} valueNode - The value that mutates the atomic variable.
  30692. * @returns {AtomicFunctionNode}
  30693. */
  30694. const atomicAnd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode );
  30695. /**
  30696. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  30697. *
  30698. * @tsl
  30699. * @function
  30700. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30701. * @param {Node} valueNode - The value that mutates the atomic variable.
  30702. * @returns {AtomicFunctionNode}
  30703. */
  30704. const atomicOr = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode );
  30705. /**
  30706. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  30707. *
  30708. * @tsl
  30709. * @function
  30710. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30711. * @param {Node} valueNode - The value that mutates the atomic variable.
  30712. * @returns {AtomicFunctionNode}
  30713. */
  30714. const atomicXor = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode );
  30715. /**
  30716. * This class represents a set of built in WGSL shader functions that sync
  30717. * synchronously execute an operation across a subgroup, or 'warp', of compute
  30718. * or fragment shader invocations within a workgroup. Typically, these functions
  30719. * will synchronously execute an operation using data from all active invocations
  30720. * within the subgroup, then broadcast that result to all active invocations. In
  30721. * other graphics APIs, subgroup functions are also referred to as wave intrinsics
  30722. * (DirectX/HLSL) or warp intrinsics (CUDA).
  30723. *
  30724. * @augments TempNode
  30725. */
  30726. class SubgroupFunctionNode extends TempNode {
  30727. static get type() {
  30728. return 'SubgroupFunctionNode';
  30729. }
  30730. /**
  30731. * Constructs a new function node.
  30732. *
  30733. * @param {string} method - The subgroup/wave intrinsic method to construct.
  30734. * @param {Node} [aNode=null] - The method's first argument.
  30735. * @param {Node} [bNode=null] - The method's second argument.
  30736. */
  30737. constructor( method, aNode = null, bNode = null ) {
  30738. super();
  30739. /**
  30740. * The subgroup/wave intrinsic method to construct.
  30741. *
  30742. * @type {string}
  30743. */
  30744. this.method = method;
  30745. /**
  30746. * The method's first argument.
  30747. *
  30748. * @type {Node}
  30749. */
  30750. this.aNode = aNode;
  30751. /**
  30752. * The method's second argument.
  30753. *
  30754. * @type {Node}
  30755. */
  30756. this.bNode = bNode;
  30757. }
  30758. getInputType( builder ) {
  30759. const aType = this.aNode ? this.aNode.getNodeType( builder ) : null;
  30760. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  30761. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  30762. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  30763. if ( aLen > bLen ) {
  30764. return aType;
  30765. } else {
  30766. return bType;
  30767. }
  30768. }
  30769. generateNodeType( builder ) {
  30770. const method = this.method;
  30771. if ( method === SubgroupFunctionNode.SUBGROUP_ELECT ) {
  30772. return 'bool';
  30773. } else if ( method === SubgroupFunctionNode.SUBGROUP_BALLOT ) {
  30774. return 'uvec4';
  30775. } else {
  30776. return this.getInputType( builder );
  30777. }
  30778. }
  30779. generate( builder, output ) {
  30780. const method = this.method;
  30781. const type = this.getNodeType( builder );
  30782. const inputType = this.getInputType( builder );
  30783. const a = this.aNode;
  30784. const b = this.bNode;
  30785. const params = [];
  30786. if (
  30787. method === SubgroupFunctionNode.SUBGROUP_BROADCAST ||
  30788. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE ||
  30789. method === SubgroupFunctionNode.QUAD_BROADCAST
  30790. ) {
  30791. const bType = b.getNodeType( builder );
  30792. params.push(
  30793. a.build( builder, type ),
  30794. b.build( builder, bType === 'float' ? 'int' : type )
  30795. );
  30796. } else if (
  30797. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ||
  30798. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ||
  30799. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP
  30800. ) {
  30801. params.push(
  30802. a.build( builder, type ),
  30803. b.build( builder, 'uint' )
  30804. );
  30805. } else {
  30806. if ( a !== null ) params.push( a.build( builder, inputType ) );
  30807. if ( b !== null ) params.push( b.build( builder, inputType ) );
  30808. }
  30809. const paramsString = params.length === 0 ? '()' : `( ${params.join( ', ' )} )`;
  30810. return builder.format( `${ builder.getMethod( method, type ) }${paramsString}`, type, output );
  30811. }
  30812. serialize( data ) {
  30813. super.serialize( data );
  30814. data.method = this.method;
  30815. }
  30816. deserialize( data ) {
  30817. super.deserialize( data );
  30818. this.method = data.method;
  30819. }
  30820. }
  30821. // 0 inputs
  30822. SubgroupFunctionNode.SUBGROUP_ELECT = 'subgroupElect';
  30823. // 1 input
  30824. SubgroupFunctionNode.SUBGROUP_BALLOT = 'subgroupBallot';
  30825. SubgroupFunctionNode.SUBGROUP_ADD = 'subgroupAdd';
  30826. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD = 'subgroupInclusiveAdd';
  30827. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND = 'subgroupExclusiveAdd';
  30828. SubgroupFunctionNode.SUBGROUP_MUL = 'subgroupMul';
  30829. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL = 'subgroupInclusiveMul';
  30830. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL = 'subgroupExclusiveMul';
  30831. SubgroupFunctionNode.SUBGROUP_AND = 'subgroupAnd';
  30832. SubgroupFunctionNode.SUBGROUP_OR = 'subgroupOr';
  30833. SubgroupFunctionNode.SUBGROUP_XOR = 'subgroupXor';
  30834. SubgroupFunctionNode.SUBGROUP_MIN = 'subgroupMin';
  30835. SubgroupFunctionNode.SUBGROUP_MAX = 'subgroupMax';
  30836. SubgroupFunctionNode.SUBGROUP_ALL = 'subgroupAll';
  30837. SubgroupFunctionNode.SUBGROUP_ANY = 'subgroupAny';
  30838. SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST = 'subgroupBroadcastFirst';
  30839. SubgroupFunctionNode.QUAD_SWAP_X = 'quadSwapX';
  30840. SubgroupFunctionNode.QUAD_SWAP_Y = 'quadSwapY';
  30841. SubgroupFunctionNode.QUAD_SWAP_DIAGONAL = 'quadSwapDiagonal';
  30842. // 2 inputs
  30843. SubgroupFunctionNode.SUBGROUP_BROADCAST = 'subgroupBroadcast';
  30844. SubgroupFunctionNode.SUBGROUP_SHUFFLE = 'subgroupShuffle';
  30845. SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR = 'subgroupShuffleXor';
  30846. SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP = 'subgroupShuffleUp';
  30847. SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN = 'subgroupShuffleDown';
  30848. SubgroupFunctionNode.QUAD_BROADCAST = 'quadBroadcast';
  30849. /**
  30850. * Returns true if this invocation has the lowest subgroup_invocation_id
  30851. * among active invocations in the subgroup.
  30852. *
  30853. * @tsl
  30854. * @method
  30855. * @return {bool} The result of the computation.
  30856. */
  30857. const subgroupElect = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ELECT ).setParameterLength( 0 );
  30858. /**
  30859. * Returns a set of bitfields where the bit corresponding to subgroup_invocation_id
  30860. * is 1 if pred is true for that active invocation and 0 otherwise.
  30861. *
  30862. * @tsl
  30863. * @method
  30864. * @param {bool} pred - A boolean that sets the bit corresponding to the invocations subgroup invocation id.
  30865. * @return {vec4<u32>}- A bitfield corresponding to the pred value of each subgroup invocation.
  30866. */
  30867. const subgroupBallot = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BALLOT ).setParameterLength( 1 );
  30868. /**
  30869. * A reduction that adds e among all active invocations and returns that result.
  30870. *
  30871. * @tsl
  30872. * @method
  30873. * @param {number} e - The value provided to the reduction by the current invocation.
  30874. * @return {number} The accumulated result of the reduction operation.
  30875. */
  30876. const subgroupAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ADD ).setParameterLength( 1 );
  30877. /**
  30878. * An inclusive scan returning the sum of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  30879. *
  30880. * @tsl
  30881. * @method
  30882. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  30883. * @return {number} The accumulated result of the inclusive scan operation.
  30884. */
  30885. const subgroupInclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD ).setParameterLength( 1 );
  30886. /**
  30887. * An exclusive scan that returns the sum of e for all active invocations with subgroup_invocation_id less than this invocation.
  30888. *
  30889. * @tsl
  30890. * @method
  30891. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  30892. * @return {number} The accumulated result of the exclusive scan operation.
  30893. */
  30894. const subgroupExclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND ).setParameterLength( 1 );
  30895. /**
  30896. * A reduction that multiplies e among all active invocations and returns that result.
  30897. *
  30898. * @tsl
  30899. * @method
  30900. * @param {number} e - The value provided to the reduction by the current invocation.
  30901. * @return {number} The accumulated result of the reduction operation.
  30902. */
  30903. const subgroupMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MUL ).setParameterLength( 1 );
  30904. /**
  30905. * An inclusive scan returning the product of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  30906. *
  30907. * @tsl
  30908. * @method
  30909. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  30910. * @return {number} The accumulated result of the inclusive scan operation.
  30911. */
  30912. const subgroupInclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL ).setParameterLength( 1 );
  30913. /**
  30914. * An exclusive scan that returns the product of e for all active invocations with subgroup_invocation_id less than this invocation.
  30915. *
  30916. * @tsl
  30917. * @method
  30918. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  30919. * @return {number} The accumulated result of the exclusive scan operation.
  30920. */
  30921. const subgroupExclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL ).setParameterLength( 1 );
  30922. /**
  30923. * A reduction that performs a bitwise and of e among all active invocations and returns that result.
  30924. *
  30925. * @tsl
  30926. * @method
  30927. * @param {number} e - The value provided to the reduction by the current invocation.
  30928. * @return {number} The result of the reduction operation.
  30929. */
  30930. const subgroupAnd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_AND ).setParameterLength( 1 );
  30931. /**
  30932. * A reduction that performs a bitwise or of e among all active invocations and returns that result.
  30933. *
  30934. * @tsl
  30935. * @method
  30936. * @param {number} e - The value provided to the reduction by the current invocation.
  30937. * @return {number} The result of the reduction operation.
  30938. */
  30939. const subgroupOr = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_OR ).setParameterLength( 1 );
  30940. /**
  30941. * A reduction that performs a bitwise xor of e among all active invocations and returns that result.
  30942. *
  30943. * @tsl
  30944. * @method
  30945. * @param {number} e - The value provided to the reduction by the current invocation.
  30946. * @return {number} The result of the reduction operation.
  30947. */
  30948. const subgroupXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_XOR ).setParameterLength( 1 );
  30949. /**
  30950. * A reduction that performs a min of e among all active invocations and returns that result.
  30951. *
  30952. * @tsl
  30953. * @method
  30954. * @param {number} e - The value provided to the reduction by the current invocation.
  30955. * @return {number} The result of the reduction operation.
  30956. */
  30957. const subgroupMin = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MIN ).setParameterLength( 1 );
  30958. /**
  30959. * A reduction that performs a max of e among all active invocations and returns that result.
  30960. *
  30961. * @tsl
  30962. * @method
  30963. * @param {number} e - The value provided to the reduction by the current invocation.
  30964. * @return {number} The result of the reduction operation.
  30965. */
  30966. const subgroupMax = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MAX ).setParameterLength( 1 );
  30967. /**
  30968. * Returns true if e is true for all active invocations in the subgroup.
  30969. *
  30970. * @tsl
  30971. * @method
  30972. * @return {bool} The result of the computation.
  30973. */
  30974. const subgroupAll = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ALL ).setParameterLength( 0 );
  30975. /**
  30976. * Returns true if e is true for any active invocation in the subgroup
  30977. *
  30978. * @tsl
  30979. * @method
  30980. * @return {bool} The result of the computation.
  30981. */
  30982. const subgroupAny = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ANY ).setParameterLength( 0 );
  30983. /**
  30984. * Broadcasts e from the active invocation with the lowest subgroup_invocation_id in the subgroup to all other active invocations.
  30985. *
  30986. * @tsl
  30987. * @method
  30988. * @param {number} e - The value to broadcast from the lowest subgroup invocation.
  30989. * @param {number} id - The subgroup invocation to broadcast from.
  30990. * @return {number} The broadcast value.
  30991. */
  30992. const subgroupBroadcastFirst = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST ).setParameterLength( 2 );
  30993. /**
  30994. * Swaps e between invocations in the quad in the X direction.
  30995. *
  30996. * @tsl
  30997. * @method
  30998. * @param {number} e - The value to swap from the current invocation.
  30999. * @return {number} The value received from the swap operation.
  31000. */
  31001. const quadSwapX = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_X ).setParameterLength( 1 );
  31002. /**
  31003. * Swaps e between invocations in the quad in the Y direction.
  31004. *
  31005. * @tsl
  31006. * @method
  31007. * @param {number} e - The value to swap from the current invocation.
  31008. * @return {number} The value received from the swap operation.
  31009. */
  31010. const quadSwapY = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_Y ).setParameterLength( 1 );
  31011. /**
  31012. * Swaps e between invocations in the quad diagonally.
  31013. *
  31014. * @tsl
  31015. * @method
  31016. * @param {number} e - The value to swap from the current invocation.
  31017. * @return {number} The value received from the swap operation.
  31018. */
  31019. const quadSwapDiagonal = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_DIAGONAL ).setParameterLength( 1 );
  31020. /**
  31021. * Broadcasts e from the invocation whose subgroup_invocation_id matches id, to all active invocations.
  31022. *
  31023. * @tsl
  31024. * @method
  31025. * @param {number} e - The value to broadcast from subgroup invocation 'id'.
  31026. * @param {number} id - The subgroup invocation to broadcast from.
  31027. * @return {number} The broadcast value.
  31028. */
  31029. const subgroupBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST ).setParameterLength( 2 );
  31030. /**
  31031. * Returns v from the active invocation whose subgroup_invocation_id matches id
  31032. *
  31033. * @tsl
  31034. * @method
  31035. * @param {number} v - The value to return from subgroup invocation id^mask.
  31036. * @param {number} id - The subgroup invocation which returns the value v.
  31037. * @return {number} The broadcast value.
  31038. */
  31039. const subgroupShuffle = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE ).setParameterLength( 2 );
  31040. /**
  31041. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id ^ mask.
  31042. *
  31043. * @tsl
  31044. * @method
  31045. * @param {number} v - The value to return from subgroup invocation id^mask.
  31046. * @param {number} mask - A bitmask that determines the target invocation via a XOR operation.
  31047. * @return {number} The broadcast value.
  31048. */
  31049. const subgroupShuffleXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ).setParameterLength( 2 );
  31050. /**
  31051. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id - delta
  31052. *
  31053. * @tsl
  31054. * @method
  31055. * @param {number} v - The value to return from subgroup invocation id^mask.
  31056. * @param {number} delta - A value that offsets the current in.
  31057. * @return {number} The broadcast value.
  31058. */
  31059. const subgroupShuffleUp = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP ).setParameterLength( 2 );
  31060. /**
  31061. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id + delta
  31062. *
  31063. * @tsl
  31064. * @method
  31065. * @param {number} v - The value to return from subgroup invocation id^mask.
  31066. * @param {number} delta - A value that offsets the current subgroup invocation.
  31067. * @return {number} The broadcast value.
  31068. */
  31069. const subgroupShuffleDown = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ).setParameterLength( 2 );
  31070. /**
  31071. * Broadcasts e from the quad invocation with id equal to id.
  31072. *
  31073. * @tsl
  31074. * @method
  31075. * @param {number} e - The value to broadcast.
  31076. * @return {number} The broadcast value.
  31077. */
  31078. const quadBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_BROADCAST ).setParameterLength( 1 );
  31079. let uniformsLib;
  31080. function getLightData( light ) {
  31081. uniformsLib = uniformsLib || new WeakMap();
  31082. let uniforms = uniformsLib.get( light );
  31083. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  31084. return uniforms;
  31085. }
  31086. /**
  31087. * TSL function for getting a shadow matrix uniform node for the given light.
  31088. *
  31089. * @tsl
  31090. * @function
  31091. * @param {Light} light -The light source.
  31092. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  31093. */
  31094. function lightShadowMatrix( light ) {
  31095. const data = getLightData( light );
  31096. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => {
  31097. // normally, shadow matrices are updated in ShadowNode. However, if the shadow matrix is used outside
  31098. // of shadow rendering (like in ProjectorLightNode), the shadow matrix still requires an update
  31099. if ( light.castShadow !== true || frame.renderer.shadowMap.enabled === false ) {
  31100. if ( light.shadow.camera.coordinateSystem !== frame.camera.coordinateSystem ) {
  31101. light.shadow.camera.coordinateSystem = frame.camera.coordinateSystem;
  31102. light.shadow.camera.updateProjectionMatrix();
  31103. }
  31104. light.shadow.updateMatrices( light );
  31105. }
  31106. return light.shadow.matrix;
  31107. } ) );
  31108. }
  31109. /**
  31110. * TSL function for getting projected uv coordinates for the given light.
  31111. * Relevant when using maps with spot lights.
  31112. *
  31113. * @tsl
  31114. * @function
  31115. * @param {Light} light -The light source.
  31116. * @param {Node<vec3>} [position=positionWorld] -The position to project.
  31117. * @returns {Node<vec3>} The projected uvs.
  31118. */
  31119. function lightProjectionUV( light, position = positionWorld ) {
  31120. const spotLightCoord = lightShadowMatrix( light ).mul( position );
  31121. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  31122. return projectionUV;
  31123. }
  31124. /**
  31125. * TSL function for getting the position in world space for the given light.
  31126. *
  31127. * @tsl
  31128. * @function
  31129. * @param {Light} light -The light source.
  31130. * @returns {UniformNode<vec3>} The light's position in world space.
  31131. */
  31132. function lightPosition( light ) {
  31133. const data = getLightData( light );
  31134. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  31135. }
  31136. /**
  31137. * TSL function for getting the light target position in world space for the given light.
  31138. *
  31139. * @tsl
  31140. * @function
  31141. * @param {Light} light -The light source.
  31142. * @returns {UniformNode<vec3>} The light target position in world space.
  31143. */
  31144. function lightTargetPosition( light ) {
  31145. const data = getLightData( light );
  31146. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  31147. }
  31148. /**
  31149. * TSL function for getting the position in view space for the given light.
  31150. *
  31151. * @tsl
  31152. * @function
  31153. * @param {Light} light - The light source.
  31154. * @returns {UniformNode<vec3>} The light's position in view space.
  31155. */
  31156. function lightViewPosition( light ) {
  31157. const data = getLightData( light );
  31158. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  31159. self.value = self.value || new Vector3();
  31160. self.value.setFromMatrixPosition( light.matrixWorld );
  31161. self.value.applyMatrix4( camera.matrixWorldInverse );
  31162. } ) );
  31163. }
  31164. /**
  31165. * TSL function for getting the light target direction for the given light.
  31166. *
  31167. * @tsl
  31168. * @function
  31169. * @param {Light} light -The light source.
  31170. * @returns {Node<vec3>} The light's target direction.
  31171. */
  31172. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  31173. /**
  31174. * A node representing the total diffuse light.
  31175. *
  31176. * @type {Node<vec3>}
  31177. */
  31178. const totalDiffuse = property( 'vec3', 'totalDiffuse' );
  31179. /**
  31180. * A node representing the total specular light.
  31181. *
  31182. * @type {Node<vec3>}
  31183. */
  31184. const totalSpecular = property( 'vec3', 'totalSpecular' );
  31185. /**
  31186. * A node representing the outgoing light.
  31187. *
  31188. * @type {Node<vec3>}
  31189. */
  31190. const outgoingLight = property( 'vec3', 'outgoingLight' );
  31191. /**
  31192. * Sorts an array of lights in ascending order by their IDs.
  31193. *
  31194. * @private
  31195. * @param {Array<Light>} lights - The array of lights to sort.
  31196. * @return {Array<Light>} The sorted array of lights.
  31197. */
  31198. const sortLights = ( lights ) => {
  31199. return lights.sort( ( a, b ) => a.id - b.id );
  31200. };
  31201. /**
  31202. * Finds and returns a lighting node associated with a specific light ID.
  31203. *
  31204. * @private
  31205. * @param {number} id - The ID of the light to search for.
  31206. * @param {Array<LightingNode>} lightNodes - The array of lighting nodes to search within.
  31207. * @return {?LightingNode} The matching lighting node, or null if not found.
  31208. */
  31209. const getLightNodeById = ( id, lightNodes ) => {
  31210. for ( const lightNode of lightNodes ) {
  31211. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  31212. return lightNode;
  31213. }
  31214. }
  31215. return null;
  31216. };
  31217. /**
  31218. * WeakMap cache mapping light objects to their corresponding lighting node instances.
  31219. *
  31220. * @private
  31221. * @type {WeakMap<Light, LightingNode>}
  31222. */
  31223. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  31224. /**
  31225. * Array used to temporarily store light IDs and shadow casting states for hashing.
  31226. *
  31227. * @private
  31228. * @type {Array<number>}
  31229. */
  31230. const _hashData = [];
  31231. /**
  31232. * This node represents the scene's lighting and manages the lighting model's life cycle
  31233. * for the current build 3D object. It is responsible for computing the total outgoing
  31234. * light in a given lighting context.
  31235. *
  31236. * @augments Node
  31237. */
  31238. class LightsNode extends Node {
  31239. static get type() {
  31240. return 'LightsNode';
  31241. }
  31242. /**
  31243. * Constructs a new lights node.
  31244. */
  31245. constructor() {
  31246. super( 'vec3' );
  31247. /**
  31248. * A node representing the total diffuse light.
  31249. *
  31250. * @type {Node<vec3>}
  31251. */
  31252. this.totalDiffuseNode = totalDiffuse;
  31253. /**
  31254. * A node representing the total specular light.
  31255. *
  31256. * @type {Node<vec3>}
  31257. */
  31258. this.totalSpecularNode = totalSpecular;
  31259. /**
  31260. * A node representing the outgoing light.
  31261. *
  31262. * @type {Node<vec3>}
  31263. */
  31264. this.outgoingLightNode = outgoingLight;
  31265. /**
  31266. * An array representing the lights in the scene.
  31267. *
  31268. * @private
  31269. * @type {Array<Light>}
  31270. */
  31271. this._lights = [];
  31272. /**
  31273. * `LightsNode` sets this property to `true` by default.
  31274. *
  31275. * @type {boolean}
  31276. * @default true
  31277. */
  31278. this.global = true;
  31279. }
  31280. /**
  31281. * Overwrites the default {@link Node#customCacheKey} implementation by including
  31282. * light data into the cache key.
  31283. *
  31284. * @return {number} The custom cache key.
  31285. */
  31286. customCacheKey() {
  31287. const builtinLights = this.getBuiltinLights();
  31288. for ( let i = 0; i < builtinLights.length; i ++ ) {
  31289. const light = builtinLights[ i ];
  31290. _hashData.push( light.id );
  31291. _hashData.push( light.castShadow ? 1 : 0 );
  31292. if ( light.isSpotLight === true ) {
  31293. const hashMap = ( light.map !== null ) ? light.map.id : -1;
  31294. const hashColorNode = ( light.colorNode ) ? light.colorNode.getCacheKey() : -1;
  31295. _hashData.push( hashMap, hashColorNode );
  31296. }
  31297. }
  31298. const cacheKey = hashArray( _hashData );
  31299. _hashData.length = 0;
  31300. return cacheKey;
  31301. }
  31302. /**
  31303. * Computes a hash value for identifying the current light nodes setup.
  31304. *
  31305. * @param {NodeBuilder} builder - A reference to the current node builder.
  31306. * @return {string} The computed hash.
  31307. */
  31308. getHash( builder ) {
  31309. const nodeData = builder.getDataFromNode( this );
  31310. if ( nodeData.lightNodesHash === undefined ) {
  31311. const lightNodes = this.setupLightsNode( builder );
  31312. nodeData.lightNodes = lightNodes;
  31313. const hash = [];
  31314. for ( const lightNode of lightNodes ) {
  31315. hash.push( lightNode.getHash() );
  31316. }
  31317. nodeData.lightNodesHash = 'lights-' + hash.join( ',' );
  31318. }
  31319. return nodeData.lightNodesHash;
  31320. }
  31321. /**
  31322. * Analyzes the node's dependencies by building all nested light nodes
  31323. * and the output node.
  31324. *
  31325. * @param {NodeBuilder} builder - A reference to the current node builder.
  31326. */
  31327. analyze( builder ) {
  31328. const properties = builder.getNodeProperties( this );
  31329. for ( const node of properties.nodes ) {
  31330. node.build( builder );
  31331. }
  31332. properties.outputNode.build( builder );
  31333. }
  31334. /**
  31335. * Creates lighting nodes for each scene light. This makes it possible to further
  31336. * process lights in the node system.
  31337. *
  31338. * @param {NodeBuilder} builder - A reference to the current node builder.
  31339. * @return {Array<LightingNode>} The array of lighting nodes.
  31340. */
  31341. setupLightsNode( builder ) {
  31342. const nodeData = builder.getDataFromNode( this );
  31343. const lightNodes = [];
  31344. const previousLightNodes = nodeData.lightNodes || null;
  31345. const materialLightings = builder.context.materialLightings;
  31346. const builtinLights = this.getBuiltinLights();
  31347. const lights = sortLights( [ ...materialLightings, ...builtinLights ] );
  31348. const nodeLibrary = builder.renderer.library;
  31349. for ( const light of lights ) {
  31350. if ( light.isNode ) {
  31351. lightNodes.push( light );
  31352. } else {
  31353. let lightNode = null;
  31354. if ( previousLightNodes !== null ) {
  31355. lightNode = getLightNodeById( light.id, previousLightNodes );
  31356. }
  31357. if ( lightNode === null ) {
  31358. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  31359. if ( lightNodeClass === null ) {
  31360. warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  31361. continue;
  31362. }
  31363. if ( _lightsNodeRef.has( light ) === false ) {
  31364. _lightsNodeRef.set( light, new lightNodeClass( light ) );
  31365. }
  31366. lightNode = _lightsNodeRef.get( light );
  31367. }
  31368. lightNodes.push( lightNode );
  31369. }
  31370. }
  31371. return lightNodes;
  31372. }
  31373. /**
  31374. * Sets up a direct light in the lighting model.
  31375. *
  31376. * @param {Object} builder - The builder object containing the context and stack.
  31377. * @param {Object} lightNode - The light node.
  31378. * @param {Object} lightData - The light object containing color and direction properties.
  31379. */
  31380. setupDirectLight( builder, lightNode, lightData ) {
  31381. const { lightingModel, reflectedLight } = builder.context;
  31382. lightingModel.direct( {
  31383. ...lightData,
  31384. lightNode,
  31385. reflectedLight
  31386. }, builder );
  31387. }
  31388. /**
  31389. * Sets up a direct rect area light in the lighting model.
  31390. *
  31391. * @param {Object} builder - The builder object containing the context and stack.
  31392. * @param {Object} lightNode - The light node.
  31393. * @param {Object} lightData - The light object containing color and area light properties.
  31394. */
  31395. setupDirectRectAreaLight( builder, lightNode, lightData ) {
  31396. const { lightingModel, reflectedLight } = builder.context;
  31397. lightingModel.directRectArea( {
  31398. ...lightData,
  31399. lightNode,
  31400. reflectedLight
  31401. }, builder );
  31402. }
  31403. /**
  31404. * Setups the internal lights by building all respective
  31405. * light nodes.
  31406. *
  31407. * @param {NodeBuilder} builder - A reference to the current node builder.
  31408. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  31409. */
  31410. setupLights( builder, lightNodes ) {
  31411. for ( const lightNode of lightNodes ) {
  31412. lightNode.build( builder );
  31413. }
  31414. }
  31415. getLightNodes( builder ) {
  31416. const nodeData = builder.getDataFromNode( this );
  31417. if ( nodeData.lightNodes === undefined ) {
  31418. nodeData.lightNodes = this.setupLightsNode( builder );
  31419. }
  31420. return nodeData.lightNodes;
  31421. }
  31422. /**
  31423. * The implementation makes sure that for each light in the scene
  31424. * there is a corresponding light node. By building the light nodes
  31425. * and evaluating the lighting model the outgoing light is computed.
  31426. *
  31427. * @param {NodeBuilder} builder - A reference to the current node builder.
  31428. * @return {Node<vec3>} A node representing the outgoing light.
  31429. */
  31430. setup( builder ) {
  31431. const currentLightsNode = builder.lightsNode;
  31432. builder.lightsNode = this;
  31433. let outgoingLightNode = this.outgoingLightNode;
  31434. const context = builder.context;
  31435. const lightingModel = context.lightingModel;
  31436. const properties = builder.getNodeProperties( this );
  31437. if ( lightingModel ) {
  31438. const { totalDiffuseNode, totalSpecularNode } = this;
  31439. context.outgoingLight = outgoingLightNode;
  31440. const stack = builder.addStack();
  31441. properties.nodes = stack.nodes;
  31442. lightingModel.start( builder );
  31443. const { backdrop, backdropAlpha } = context;
  31444. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  31445. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  31446. if ( backdrop !== null ) {
  31447. if ( backdropAlpha !== null ) {
  31448. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  31449. } else {
  31450. totalDiffuse = vec3( backdrop );
  31451. }
  31452. }
  31453. totalDiffuseNode.assign( totalDiffuse );
  31454. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  31455. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  31456. lightingModel.finish( builder );
  31457. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  31458. } else {
  31459. properties.nodes = [];
  31460. }
  31461. builder.lightsNode = currentLightsNode;
  31462. return outgoingLightNode;
  31463. }
  31464. /**
  31465. * Configures this node with an array of lights.
  31466. *
  31467. * @param {Array<Light>} lights - An array of lights.
  31468. * @return {LightsNode} A reference to this node.
  31469. */
  31470. setLights( lights ) {
  31471. this._lights = lights;
  31472. return this;
  31473. }
  31474. /**
  31475. * Returns an array of the scene's lights.
  31476. *
  31477. * @return {Array<Light>} The scene's lights.
  31478. */
  31479. getLights() {
  31480. return this._lights;
  31481. }
  31482. /**
  31483. * Returns an array of the scene's lights.
  31484. *
  31485. * The light variations are shader-dependent;
  31486. * if this array changes, the shader needs to be recreated.
  31487. *
  31488. * @return {Array<Light>} The scene's lights.
  31489. */
  31490. getBuiltinLights() {
  31491. return this._lights;
  31492. }
  31493. /**
  31494. * Whether the scene has lights or not.
  31495. *
  31496. * @type {boolean}
  31497. */
  31498. get hasLights() {
  31499. return this._lights.length > 0;
  31500. }
  31501. }
  31502. /**
  31503. * TSL function for creating an instance of `LightsNode` and configuring
  31504. * it with the given array of lights.
  31505. *
  31506. * @tsl
  31507. * @function
  31508. * @param {Array<Light>} lights - An array of lights.
  31509. * @return {LightsNode} The created lights node.
  31510. */
  31511. const lights = ( lights = [] ) => new LightsNode().setLights( lights );
  31512. /**
  31513. * Base class for all shadow nodes.
  31514. *
  31515. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  31516. * Lighting nodes might share the same shadow node type or use specific ones depending on
  31517. * their requirements.
  31518. *
  31519. * @augments Node
  31520. */
  31521. class ShadowBaseNode extends Node {
  31522. static get type() {
  31523. return 'ShadowBaseNode';
  31524. }
  31525. /**
  31526. * Constructs a new shadow base node.
  31527. *
  31528. * @param {Light} light - The shadow casting light.
  31529. */
  31530. constructor( light ) {
  31531. super();
  31532. /**
  31533. * The shadow casting light.
  31534. *
  31535. * @type {Light}
  31536. */
  31537. this.light = light;
  31538. /**
  31539. * Overwritten since shadows are updated by default per render.
  31540. *
  31541. * @type {string}
  31542. * @default 'render'
  31543. */
  31544. this.updateBeforeType = NodeUpdateType.RENDER;
  31545. /**
  31546. * This flag can be used for type testing.
  31547. *
  31548. * @type {boolean}
  31549. * @readonly
  31550. * @default true
  31551. */
  31552. this.isShadowBaseNode = true;
  31553. }
  31554. /**
  31555. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  31556. *
  31557. * @param {NodeBuilder} object - A configuration object that must at least hold a material reference.
  31558. */
  31559. setupShadowPosition( { context, material } ) {
  31560. // Use assign inside an Fn()
  31561. shadowPositionWorld.assign( material.receivedShadowPositionNode || context.shadowPositionWorld || positionWorld );
  31562. }
  31563. }
  31564. /**
  31565. * TSL object that represents the vertex position in world space during the shadow pass.
  31566. *
  31567. * @tsl
  31568. * @type {Node<vec3>}
  31569. */
  31570. const shadowPositionWorld = /*@__PURE__*/ property( 'vec3', 'shadowPositionWorld' );
  31571. /**
  31572. * Saves the state of the given renderer and stores it into the given state object.
  31573. *
  31574. * If not state object is provided, the function creates one.
  31575. *
  31576. * @private
  31577. * @function
  31578. * @param {Renderer} renderer - The renderer.
  31579. * @param {Object} [state={}] - The state.
  31580. * @return {Object} The state.
  31581. */
  31582. function saveRendererState( renderer, state = {} ) {
  31583. state.toneMapping = renderer.toneMapping;
  31584. state.toneMappingExposure = renderer.toneMappingExposure;
  31585. state.outputColorSpace = renderer.outputColorSpace;
  31586. state.renderTarget = renderer.getRenderTarget();
  31587. state.activeCubeFace = renderer.getActiveCubeFace();
  31588. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  31589. state.renderObjectFunction = renderer.getRenderObjectFunction();
  31590. state.pixelRatio = renderer.getPixelRatio();
  31591. state.mrt = renderer.getMRT();
  31592. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  31593. state.clearAlpha = renderer.getClearAlpha();
  31594. state.autoClear = renderer.autoClear;
  31595. state.scissorTest = renderer.getScissorTest();
  31596. return state;
  31597. }
  31598. /**
  31599. * Saves the state of the given renderer and stores it into the given state object.
  31600. * Besides, the function also resets the state of the renderer to its default values.
  31601. *
  31602. * If not state object is provided, the function creates one.
  31603. *
  31604. * @private
  31605. * @function
  31606. * @param {Renderer} renderer - The renderer.
  31607. * @param {Object} [state={}] - The state.
  31608. * @return {Object} The state.
  31609. */
  31610. function resetRendererState( renderer, state ) {
  31611. state = saveRendererState( renderer, state );
  31612. renderer.setMRT( null );
  31613. renderer.setRenderObjectFunction( null );
  31614. renderer.setClearColor( 0x000000, 1 );
  31615. renderer.autoClear = true;
  31616. return state;
  31617. }
  31618. /**
  31619. * Restores the state of the given renderer from the given state object.
  31620. *
  31621. * @private
  31622. * @function
  31623. * @param {Renderer} renderer - The renderer.
  31624. * @param {Object} state - The state to restore.
  31625. */
  31626. function restoreRendererState( renderer, state ) {
  31627. renderer.toneMapping = state.toneMapping;
  31628. renderer.toneMappingExposure = state.toneMappingExposure;
  31629. renderer.outputColorSpace = state.outputColorSpace;
  31630. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  31631. renderer.setRenderObjectFunction( state.renderObjectFunction );
  31632. renderer.setPixelRatio( state.pixelRatio );
  31633. renderer.setMRT( state.mrt );
  31634. renderer.setClearColor( state.clearColor, state.clearAlpha );
  31635. renderer.autoClear = state.autoClear;
  31636. renderer.setScissorTest( state.scissorTest );
  31637. }
  31638. /**
  31639. * Saves the state of the given scene and stores it into the given state object.
  31640. *
  31641. * If not state object is provided, the function creates one.
  31642. *
  31643. * @private
  31644. * @function
  31645. * @param {Scene} scene - The scene.
  31646. * @param {Object} [state={}] - The state.
  31647. * @return {Object} The state.
  31648. */
  31649. function saveSceneState( scene, state = {} ) {
  31650. state.background = scene.background;
  31651. state.backgroundNode = scene.backgroundNode;
  31652. state.overrideMaterial = scene.overrideMaterial;
  31653. return state;
  31654. }
  31655. /**
  31656. * Saves the state of the given scene and stores it into the given state object.
  31657. * Besides, the function also resets the state of the scene to its default values.
  31658. *
  31659. * If not state object is provided, the function creates one.
  31660. *
  31661. * @private
  31662. * @function
  31663. * @param {Scene} scene - The scene.
  31664. * @param {Object} [state={}] - The state.
  31665. * @return {Object} The state.
  31666. */
  31667. function resetSceneState( scene, state ) {
  31668. state = saveSceneState( scene, state );
  31669. scene.background = null;
  31670. scene.backgroundNode = null;
  31671. scene.overrideMaterial = null;
  31672. return state;
  31673. }
  31674. /**
  31675. * Restores the state of the given scene from the given state object.
  31676. *
  31677. * @private
  31678. * @function
  31679. * @param {Scene} scene - The scene.
  31680. * @param {Object} state - The state to restore.
  31681. */
  31682. function restoreSceneState( scene, state ) {
  31683. scene.background = state.background;
  31684. scene.backgroundNode = state.backgroundNode;
  31685. scene.overrideMaterial = state.overrideMaterial;
  31686. }
  31687. /**
  31688. * Saves the state of the given renderer and scene and stores it into the given state object.
  31689. *
  31690. * If not state object is provided, the function creates one.
  31691. *
  31692. * @private
  31693. * @function
  31694. * @param {Renderer} renderer - The renderer.
  31695. * @param {Scene} scene - The scene.
  31696. * @param {Object} [state={}] - The state.
  31697. * @return {Object} The state.
  31698. */
  31699. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  31700. state = saveRendererState( renderer, state );
  31701. state = saveSceneState( scene, state );
  31702. return state;
  31703. }
  31704. /**
  31705. * Saves the state of the given renderer and scene and stores it into the given state object.
  31706. * Besides, the function also resets the state of the renderer and scene to its default values.
  31707. *
  31708. * If not state object is provided, the function creates one.
  31709. *
  31710. * @private
  31711. * @function
  31712. * @param {Renderer} renderer - The renderer.
  31713. * @param {Scene} scene - The scene.
  31714. * @param {Object} [state={}] - The state.
  31715. * @return {Object} The state.
  31716. */
  31717. function resetRendererAndSceneState( renderer, scene, state ) {
  31718. state = resetRendererState( renderer, state );
  31719. state = resetSceneState( scene, state );
  31720. return state;
  31721. }
  31722. /**
  31723. * Restores the state of the given renderer and scene from the given state object.
  31724. *
  31725. * @private
  31726. * @function
  31727. * @param {Renderer} renderer - The renderer.
  31728. * @param {Scene} scene - The scene.
  31729. * @param {Object} state - The state to restore.
  31730. */
  31731. function restoreRendererAndSceneState( renderer, scene, state ) {
  31732. restoreRendererState( renderer, state );
  31733. restoreSceneState( scene, state );
  31734. }
  31735. var RendererUtils = /*#__PURE__*/Object.freeze({
  31736. __proto__: null,
  31737. resetRendererAndSceneState: resetRendererAndSceneState,
  31738. resetRendererState: resetRendererState,
  31739. resetSceneState: resetSceneState,
  31740. restoreRendererAndSceneState: restoreRendererAndSceneState,
  31741. restoreRendererState: restoreRendererState,
  31742. restoreSceneState: restoreSceneState,
  31743. saveRendererAndSceneState: saveRendererAndSceneState,
  31744. saveRendererState: saveRendererState,
  31745. saveSceneState: saveSceneState
  31746. });
  31747. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  31748. /**
  31749. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  31750. * with a binary `[0,1]` result.
  31751. *
  31752. * @method
  31753. * @param {Object} inputs - The input parameter object.
  31754. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  31755. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  31756. * @return {Node<float>} The filtering result.
  31757. */
  31758. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  31759. let basic = texture( depthTexture, shadowCoord.xy ).setName( 't_basic' );
  31760. if ( depthTexture.isArrayTexture ) {
  31761. basic = basic.depth( depthLayer );
  31762. }
  31763. return basic.compare( shadowCoord.z );
  31764. } );
  31765. /**
  31766. * A shadow filtering function performing PCF filtering with Vogel disk sampling and IGN.
  31767. *
  31768. * Uses 5 samples distributed via Vogel disk pattern, rotated per-pixel using Interleaved
  31769. * Gradient Noise (IGN) to break up banding artifacts. Combined with hardware PCF (4-tap
  31770. * filtering per sample), this effectively provides 20 filtered taps with better distribution.
  31771. *
  31772. * @method
  31773. * @param {Object} inputs - The input parameter object.
  31774. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  31775. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  31776. * @param {LightShadow} inputs.shadow - The light shadow.
  31777. * @return {Node<float>} The filtering result.
  31778. */
  31779. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  31780. const depthCompare = ( uv, compare ) => {
  31781. let depth = texture( depthTexture, uv );
  31782. if ( depthTexture.isArrayTexture ) {
  31783. depth = depth.depth( depthLayer );
  31784. }
  31785. return depth.compare( compare );
  31786. };
  31787. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  31788. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  31789. const texelSize = vec2( 1 ).div( mapSize );
  31790. const radiusScaled = radius.mul( texelSize.x );
  31791. // Use IGN to rotate sampling pattern per pixel (phi = IGN * 2π)
  31792. const phi = interleavedGradientNoise( screenCoordinate.xy ).mul( 6.28318530718 );
  31793. // 5 samples using Vogel disk distribution
  31794. return add(
  31795. depthCompare( shadowCoord.xy.add( vogelDiskSample( 0, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  31796. depthCompare( shadowCoord.xy.add( vogelDiskSample( 1, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  31797. depthCompare( shadowCoord.xy.add( vogelDiskSample( 2, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  31798. depthCompare( shadowCoord.xy.add( vogelDiskSample( 3, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  31799. depthCompare( shadowCoord.xy.add( vogelDiskSample( 4, 5, phi ).mul( radiusScaled ) ), shadowCoord.z )
  31800. ).mul( 1 / 5 );
  31801. } );
  31802. /**
  31803. * A shadow filtering function performing VSM filtering.
  31804. *
  31805. * @method
  31806. * @param {Object} inputs - The input parameter object.
  31807. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  31808. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  31809. * @return {Node<float>} The filtering result.
  31810. */
  31811. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer }, builder ) => {
  31812. let distribution = texture( depthTexture ).sample( shadowCoord.xy );
  31813. if ( depthTexture.isArrayTexture ) {
  31814. distribution = distribution.depth( depthLayer );
  31815. }
  31816. distribution = distribution.rg;
  31817. const mean = distribution.x;
  31818. const variance = max$1( 0.0000001, distribution.y.mul( distribution.y ) );
  31819. const hardShadow = ( builder.renderer.reversedDepthBuffer ) ? step( mean, shadowCoord.z ) : step( shadowCoord.z, mean );
  31820. const output = float( 1 ).toVar(); // default, fully lit
  31821. If( hardShadow.notEqual( 1.0 ), () => {
  31822. // Distance from mean
  31823. const d = shadowCoord.z.sub( mean );
  31824. // Chebyshev's inequality for upper bound on probability
  31825. let p_max = variance.div( variance.add( d.mul( d ) ) );
  31826. // Reduce light bleeding by remapping [amount, 1] to [0, 1]
  31827. p_max = clamp( sub( p_max, 0.3 ).div( 0.65 ) );
  31828. output.assign( max$1( hardShadow, p_max ) );
  31829. } );
  31830. return output;
  31831. } );
  31832. /**
  31833. * Retrieves or creates a shadow material for the given light source.
  31834. *
  31835. * This function checks if a shadow material already exists for the provided light.
  31836. * If not, it creates a new `NodeMaterial` configured for shadow rendering and stores it
  31837. * in the `shadowMaterialLib` for future use.
  31838. *
  31839. * @tsl
  31840. * @function
  31841. * @param {Light} light - The light source for which the shadow material is needed.
  31842. * If the light is a point light, a depth node is calculated
  31843. * using the linear shadow distance.
  31844. * @returns {NodeMaterial} The shadow material associated with the given light.
  31845. */
  31846. const getShadowMaterial = ( light ) => {
  31847. let material = shadowMaterialLib.get( light );
  31848. if ( material === undefined ) {
  31849. material = new NodeMaterial();
  31850. material.colorNode = vec4( 0, 0, 0, 1 );
  31851. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  31852. material.name = 'ShadowMaterial';
  31853. material.blending = NoBlending;
  31854. material.fog = false;
  31855. shadowMaterialLib.set( light, material );
  31856. }
  31857. return material;
  31858. };
  31859. /**
  31860. * Disposes the shadow material for the given light source.
  31861. *
  31862. * @param {Light} light - The light source.
  31863. */
  31864. const disposeShadowMaterial = ( light ) => {
  31865. const material = shadowMaterialLib.get( light );
  31866. if ( material !== undefined ) {
  31867. material.dispose();
  31868. shadowMaterialLib.delete( light );
  31869. }
  31870. };
  31871. //
  31872. const _shadowRenderObjectLibrary = /*@__PURE__*/ new ChainMap();
  31873. const _shadowRenderObjectKeys = [];
  31874. /**
  31875. * Creates a function to render shadow objects in a scene.
  31876. *
  31877. * @tsl
  31878. * @function
  31879. * @param {Renderer} renderer - The renderer.
  31880. * @param {LightShadow} shadow - The light shadow object containing shadow properties.
  31881. * @param {number} shadowType - The type of shadow map (e.g., BasicShadowMap).
  31882. * @param {boolean} useVelocity - Whether to use velocity data for rendering.
  31883. * @return {shadowRenderObjectFunction} A function that renders shadow objects.
  31884. */
  31885. const getShadowRenderObjectFunction = ( renderer, shadow, shadowType, useVelocity ) => {
  31886. _shadowRenderObjectKeys[ 0 ] = renderer;
  31887. _shadowRenderObjectKeys[ 1 ] = shadow;
  31888. let renderObjectFunction = _shadowRenderObjectLibrary.get( _shadowRenderObjectKeys );
  31889. if ( renderObjectFunction === undefined || ( renderObjectFunction.shadowType !== shadowType || renderObjectFunction.useVelocity !== useVelocity ) ) {
  31890. renderObjectFunction = ( object, scene, _camera, geometry, material, group, lightsNode, clippingContext, passId ) => {
  31891. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  31892. if ( useVelocity ) {
  31893. getDataFromObject( object ).useVelocity = true;
  31894. }
  31895. object.onBeforeShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  31896. renderer.renderObject( object, scene, _camera, geometry, material, group, lightsNode, clippingContext, passId );
  31897. object.onAfterShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  31898. }
  31899. };
  31900. renderObjectFunction.shadowType = shadowType;
  31901. renderObjectFunction.useVelocity = useVelocity;
  31902. _shadowRenderObjectLibrary.set( _shadowRenderObjectKeys, renderObjectFunction );
  31903. }
  31904. _shadowRenderObjectKeys[ 0 ] = null;
  31905. _shadowRenderObjectKeys[ 1 ] = null;
  31906. return renderObjectFunction;
  31907. };
  31908. /**
  31909. * Represents the shader code for the first VSM render pass.
  31910. *
  31911. * @private
  31912. * @method
  31913. * @param {Object} inputs - The input parameter object.
  31914. * @param {Node<float>} inputs.samples - The number of samples
  31915. * @param {Node<float>} inputs.radius - The radius.
  31916. * @param {Node<float>} inputs.size - The size.
  31917. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  31918. * @return {Node<vec2>} The VSM output.
  31919. */
  31920. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  31921. const mean = float( 0 ).toVar( 'meanVertical' );
  31922. const squaredMean = float( 0 ).toVar( 'squareMeanVertical' );
  31923. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  31924. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  31925. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  31926. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  31927. let depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) );
  31928. if ( shadowPass.value.isArrayTexture ) {
  31929. depth = depth.depth( depthLayer );
  31930. }
  31931. depth = depth.x;
  31932. mean.addAssign( depth );
  31933. squaredMean.addAssign( depth.mul( depth ) );
  31934. } );
  31935. mean.divAssign( samples );
  31936. squaredMean.divAssign( samples );
  31937. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ).max( 0 ) );
  31938. return vec2( mean, std_dev );
  31939. } );
  31940. /**
  31941. * Represents the shader code for the second VSM render pass.
  31942. *
  31943. * @private
  31944. * @method
  31945. * @param {Object} inputs - The input parameter object.
  31946. * @param {Node<float>} inputs.samples - The number of samples
  31947. * @param {Node<float>} inputs.radius - The radius.
  31948. * @param {Node<float>} inputs.size - The size.
  31949. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  31950. * @return {Node<vec2>} The VSM output.
  31951. */
  31952. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  31953. const mean = float( 0 ).toVar( 'meanHorizontal' );
  31954. const squaredMean = float( 0 ).toVar( 'squareMeanHorizontal' );
  31955. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  31956. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  31957. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  31958. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  31959. let distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  31960. if ( shadowPass.value.isArrayTexture ) {
  31961. distribution = distribution.depth( depthLayer );
  31962. }
  31963. mean.addAssign( distribution.x );
  31964. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  31965. } );
  31966. mean.divAssign( samples );
  31967. squaredMean.divAssign( samples );
  31968. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ).max( 0 ) );
  31969. return vec2( mean, std_dev );
  31970. } );
  31971. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, null /* PCFSoftShadowMap, removed */, VSMShadowFilter ];
  31972. //
  31973. let _rendererState;
  31974. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  31975. /**
  31976. * Represents the default shadow implementation for lighting nodes.
  31977. *
  31978. * @augments ShadowBaseNode
  31979. */
  31980. class ShadowNode extends ShadowBaseNode {
  31981. static get type() {
  31982. return 'ShadowNode';
  31983. }
  31984. /**
  31985. * Constructs a new shadow node.
  31986. *
  31987. * @param {Light} light - The shadow casting light.
  31988. * @param {?LightShadow} [shadow=null] - An optional light shadow.
  31989. */
  31990. constructor( light, shadow = null ) {
  31991. super( light );
  31992. /**
  31993. * The light shadow which defines the properties light's
  31994. * shadow.
  31995. *
  31996. * @type {?LightShadow}
  31997. * @default null
  31998. */
  31999. this.shadow = shadow || light.shadow;
  32000. /**
  32001. * A reference to the shadow map which is a render target.
  32002. *
  32003. * @type {?RenderTarget}
  32004. * @default null
  32005. */
  32006. this.shadowMap = null;
  32007. /**
  32008. * Only relevant for VSM shadows. Render target for the
  32009. * first VSM render pass.
  32010. *
  32011. * @type {?RenderTarget}
  32012. * @default null
  32013. */
  32014. this.vsmShadowMapVertical = null;
  32015. /**
  32016. * Only relevant for VSM shadows. Render target for the
  32017. * second VSM render pass.
  32018. *
  32019. * @type {?RenderTarget}
  32020. * @default null
  32021. */
  32022. this.vsmShadowMapHorizontal = null;
  32023. /**
  32024. * Only relevant for VSM shadows. Node material which
  32025. * is used to render the first VSM pass.
  32026. *
  32027. * @type {?NodeMaterial}
  32028. * @default null
  32029. */
  32030. this.vsmMaterialVertical = null;
  32031. /**
  32032. * Only relevant for VSM shadows. Node material which
  32033. * is used to render the second VSM pass.
  32034. *
  32035. * @type {?NodeMaterial}
  32036. * @default null
  32037. */
  32038. this.vsmMaterialHorizontal = null;
  32039. /**
  32040. * A reference to the output node which defines the
  32041. * final result of this shadow node.
  32042. *
  32043. * @type {?Node}
  32044. * @private
  32045. * @default null
  32046. */
  32047. this._node = null;
  32048. /**
  32049. * The current shadow map type of this shadow node.
  32050. *
  32051. * @type {?number}
  32052. * @private
  32053. * @default null
  32054. */
  32055. this._currentShadowType = null;
  32056. /**
  32057. * A Weak Map holding the current frame ID per camera. Used
  32058. * to control the update of shadow maps.
  32059. *
  32060. * @type {WeakMap<Camera,number>}
  32061. * @private
  32062. */
  32063. this._cameraFrameId = new WeakMap();
  32064. /**
  32065. * This flag can be used for type testing.
  32066. *
  32067. * @type {boolean}
  32068. * @readonly
  32069. * @default true
  32070. */
  32071. this.isShadowNode = true;
  32072. /**
  32073. * This index can be used when overriding setupRenderTarget with a RenderTarget Array to specify the depth layer.
  32074. *
  32075. * @type {number}
  32076. * @readonly
  32077. * @default true
  32078. */
  32079. this.depthLayer = 0;
  32080. }
  32081. /**
  32082. * Setups the shadow filtering.
  32083. *
  32084. * @param {NodeBuilder} builder - A reference to the current node builder.
  32085. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  32086. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  32087. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  32088. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  32089. * @param {LightShadow} inputs.shadow - The light shadow.
  32090. * @return {Node<float>} The result node of the shadow filtering.
  32091. */
  32092. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow, depthLayer } ) {
  32093. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  32094. .and( shadowCoord.x.lessThanEqual( 1 ) )
  32095. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  32096. .and( shadowCoord.y.lessThanEqual( 1 ) )
  32097. .and( shadowCoord.z.lessThanEqual( 1 ) );
  32098. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow, depthLayer } );
  32099. return frustumTest.select( shadowNode, float( 1 ) );
  32100. }
  32101. /**
  32102. * Setups the shadow coordinates.
  32103. *
  32104. * @param {NodeBuilder} builder - A reference to the current node builder.
  32105. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  32106. * @return {Node<vec3>} The shadow coordinates.
  32107. */
  32108. setupShadowCoord( builder, shadowPosition ) {
  32109. const { shadow } = this;
  32110. const { renderer } = builder;
  32111. const bias = shadow.biasNode || reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  32112. let shadowCoord = shadowPosition;
  32113. let coordZ;
  32114. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  32115. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  32116. coordZ = shadowCoord.z;
  32117. } else {
  32118. const w = shadowCoord.w;
  32119. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  32120. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  32121. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  32122. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  32123. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  32124. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  32125. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  32126. }
  32127. shadowCoord = vec3(
  32128. shadowCoord.x,
  32129. shadowCoord.y.oneMinus(), // follow webgpu standards
  32130. renderer.reversedDepthBuffer ? coordZ.sub( bias ) : coordZ.add( bias )
  32131. );
  32132. return shadowCoord;
  32133. }
  32134. /**
  32135. * Returns the shadow filtering function for the given shadow type.
  32136. *
  32137. * @param {number} type - The shadow type.
  32138. * @return {Function} The filtering function.
  32139. */
  32140. getShadowFilterFn( type ) {
  32141. return _shadowFilterLib[ type ];
  32142. }
  32143. setupRenderTarget( shadow, builder ) {
  32144. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  32145. depthTexture.name = 'ShadowDepthTexture';
  32146. depthTexture.compareFunction = builder.renderer.reversedDepthBuffer ? GreaterEqualCompare : LessEqualCompare;
  32147. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  32148. shadowMap.texture.name = 'ShadowMap';
  32149. shadowMap.texture.type = shadow.mapType;
  32150. shadowMap.depthTexture = depthTexture;
  32151. return { shadowMap, depthTexture };
  32152. }
  32153. /**
  32154. * Setups the shadow output node.
  32155. *
  32156. * @param {NodeBuilder} builder - A reference to the current node builder.
  32157. * @return {Node<vec3>} The shadow output node.
  32158. */
  32159. setupShadow( builder ) {
  32160. const { renderer, camera } = builder;
  32161. const { light, shadow } = this;
  32162. const { depthTexture, shadowMap } = this.setupRenderTarget( shadow, builder );
  32163. const shadowMapType = renderer.shadowMap.type;
  32164. const hasTextureCompare = renderer.hasCompatibility( Compatibility.TEXTURE_COMPARE );
  32165. if ( shadowMapType === PCFShadowMap && hasTextureCompare ) {
  32166. depthTexture.minFilter = LinearFilter;
  32167. depthTexture.magFilter = LinearFilter;
  32168. } else {
  32169. depthTexture.minFilter = NearestFilter;
  32170. depthTexture.magFilter = NearestFilter;
  32171. }
  32172. shadow.camera.coordinateSystem = camera.coordinateSystem;
  32173. shadow.camera.updateProjectionMatrix();
  32174. // VSM
  32175. if ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  32176. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  32177. if ( shadowMap.depth > 1 ) {
  32178. if ( ! shadowMap._vsmShadowMapVertical ) {
  32179. shadowMap._vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  32180. shadowMap._vsmShadowMapVertical.texture.name = 'VSMVertical';
  32181. }
  32182. this.vsmShadowMapVertical = shadowMap._vsmShadowMapVertical;
  32183. if ( ! shadowMap._vsmShadowMapHorizontal ) {
  32184. shadowMap._vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  32185. shadowMap._vsmShadowMapHorizontal.texture.name = 'VSMHorizontal';
  32186. }
  32187. this.vsmShadowMapHorizontal = shadowMap._vsmShadowMapHorizontal;
  32188. } else {
  32189. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  32190. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  32191. }
  32192. let shadowPassVertical = texture( depthTexture );
  32193. if ( depthTexture.isArrayTexture ) {
  32194. shadowPassVertical = shadowPassVertical.depth( this.depthLayer );
  32195. }
  32196. let shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  32197. if ( depthTexture.isArrayTexture ) {
  32198. shadowPassHorizontal = shadowPassHorizontal.depth( this.depthLayer );
  32199. }
  32200. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  32201. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  32202. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  32203. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  32204. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  32205. material.name = 'VSMVertical';
  32206. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  32207. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  32208. material.name = 'VSMHorizontal';
  32209. }
  32210. //
  32211. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  32212. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  32213. const shadowMatrix = lightShadowMatrix( light );
  32214. const shadowNormalBias = normalWorld.mul( normalBias );
  32215. let shadowPosition;
  32216. if ( ! renderer.highPrecision || builder.material.receivedShadowPositionNode || builder.context.shadowPositionWorld ) {
  32217. shadowPosition = shadowMatrix.mul( shadowPositionWorld.add( shadowNormalBias ) );
  32218. } else {
  32219. const highpShadowModelMatrix = uniform( 'mat4' ).onObjectUpdate( ( { object }, self ) => {
  32220. return self.value.multiplyMatrices( shadowMatrix.value, object.matrixWorld );
  32221. } );
  32222. shadowPosition = highpShadowModelMatrix.mul( positionLocal ).add( shadowMatrix.mul( vec4( shadowNormalBias, 0 ) ) );
  32223. }
  32224. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  32225. //
  32226. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  32227. if ( filterFn === null ) {
  32228. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  32229. }
  32230. const shadowDepthTexture = ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  32231. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow, depthLayer: this.depthLayer } );
  32232. let shadowColor;
  32233. if ( renderer.shadowMap.transmitted === true ) {
  32234. if ( shadowMap.texture.isCubeTexture ) {
  32235. // For cube shadow maps (point lights), use cubeTexture with vec3 coordinates
  32236. shadowColor = cubeTexture( shadowMap.texture, shadowCoord.xyz );
  32237. } else {
  32238. shadowColor = texture( shadowMap.texture, shadowCoord );
  32239. if ( depthTexture.isArrayTexture ) {
  32240. shadowColor = shadowColor.depth( this.depthLayer );
  32241. }
  32242. }
  32243. }
  32244. //
  32245. let shadowOutput;
  32246. if ( shadowColor ) {
  32247. shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  32248. } else {
  32249. shadowOutput = mix( 1, shadowNode, shadowIntensity ).toVar();
  32250. }
  32251. this.shadowMap = shadowMap;
  32252. this.shadow.map = shadowMap;
  32253. // Shadow Output + Inspector
  32254. const inspectName = `${ this.light.type } Shadow [ ${ this.light.name || 'ID: ' + this.light.id } ]`;
  32255. if ( shadowColor ) {
  32256. shadowOutput.toInspector( `${ inspectName } / Color`, () => {
  32257. if ( this.shadowMap.texture.isCubeTexture ) {
  32258. return cubeTexture( this.shadowMap.texture, equirectDirection() );
  32259. }
  32260. return texture( this.shadowMap.texture );
  32261. } );
  32262. }
  32263. return shadowOutput.toInspector( `${ inspectName } / Depth`, () => {
  32264. const shadowCameraNear = reference( 'near', 'float', this.shadow.camera );
  32265. const shadowCameraFar = reference( 'far', 'float', this.shadow.camera );
  32266. let depthNode;
  32267. if ( this.shadowMap.texture.isCubeTexture ) {
  32268. depthNode = cubeTexture( this.shadowMap.depthTexture, equirectDirection() ).r;
  32269. } else {
  32270. depthNode = texture( this.shadowMap.depthTexture ).r;
  32271. }
  32272. let linearDepth;
  32273. if ( this.shadow.camera.isPerspectiveCamera ) {
  32274. linearDepth = perspectiveDepthToViewZ( depthNode, shadowCameraNear, shadowCameraFar );
  32275. } else {
  32276. linearDepth = orthographicDepthToViewZ( depthNode, shadowCameraNear, shadowCameraFar );
  32277. }
  32278. linearDepth = viewZToOrthographicDepth( linearDepth, shadowCameraNear, shadowCameraFar );
  32279. return linearDepth.oneMinus();
  32280. } );
  32281. }
  32282. /**
  32283. * The implementation performs the setup of the output node. An output is only
  32284. * produces if shadow mapping is globally enabled in the renderer.
  32285. *
  32286. * @param {NodeBuilder} builder - A reference to the current node builder.
  32287. * @return {ShaderCallNodeInternal} The output node.
  32288. */
  32289. setup( builder ) {
  32290. if ( builder.renderer.shadowMap.enabled === false ) return;
  32291. return Fn( () => {
  32292. const currentShadowType = builder.renderer.shadowMap.type;
  32293. if ( this._currentShadowType !== currentShadowType ) {
  32294. this._reset();
  32295. this._node = null;
  32296. }
  32297. let node = this._node;
  32298. this.setupShadowPosition( builder );
  32299. if ( node === null ) {
  32300. this._node = node = this.setupShadow( builder );
  32301. this._currentShadowType = currentShadowType;
  32302. }
  32303. if ( builder.material.receivedShadowNode ) {
  32304. node = builder.material.receivedShadowNode( node );
  32305. }
  32306. return node;
  32307. } )();
  32308. }
  32309. /**
  32310. * Renders the shadow. The logic of this function could be included
  32311. * into {@link ShadowNode#updateShadow} however more specialized shadow
  32312. * nodes might require a custom shadow map rendering. By having a
  32313. * dedicated method, it's easier to overwrite the default behavior.
  32314. *
  32315. * @param {NodeFrame} frame - A reference to the current node frame.
  32316. */
  32317. renderShadow( frame ) {
  32318. const { shadow, shadowMap, light } = this;
  32319. const { renderer, scene } = frame;
  32320. shadow.updateMatrices( light );
  32321. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height, shadowMap.depth );
  32322. const currentSceneName = scene.name;
  32323. scene.name = `Shadow Map [ ${ light.name || 'ID: ' + light.id } ]`;
  32324. renderer.render( scene, shadow.camera );
  32325. scene.name = currentSceneName;
  32326. }
  32327. /**
  32328. * Updates the shadow.
  32329. *
  32330. * @param {NodeFrame} frame - A reference to the current node frame.
  32331. */
  32332. updateShadow( frame ) {
  32333. const { shadowMap, light, shadow } = this;
  32334. const { renderer, scene, camera } = frame;
  32335. const shadowType = renderer.shadowMap.type;
  32336. const depthVersion = shadowMap.depthTexture.version;
  32337. this._depthVersionCached = depthVersion;
  32338. const _shadowCameraLayer = shadow.camera.layers.mask;
  32339. if ( ( shadow.camera.layers.mask & 0xFFFFFFFE ) === 0 ) {
  32340. shadow.camera.layers.mask = camera.layers.mask;
  32341. }
  32342. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  32343. const currentMRT = renderer.getMRT();
  32344. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  32345. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  32346. scene.overrideMaterial = getShadowMaterial( light );
  32347. renderer.setRenderObjectFunction( getShadowRenderObjectFunction( renderer, shadow, shadowType, useVelocity ) );
  32348. renderer.setClearColor( 0x000000, 0 );
  32349. renderer.setRenderTarget( shadowMap );
  32350. this.renderShadow( frame );
  32351. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  32352. // vsm blur pass
  32353. if ( shadowType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  32354. this.vsmPass( renderer );
  32355. }
  32356. shadow.camera.layers.mask = _shadowCameraLayer;
  32357. restoreRendererAndSceneState( renderer, scene, _rendererState );
  32358. }
  32359. /**
  32360. * For VSM additional render passes are required.
  32361. *
  32362. * @param {Renderer} renderer - A reference to the current renderer.
  32363. */
  32364. vsmPass( renderer ) {
  32365. const { shadow } = this;
  32366. const depth = this.shadowMap.depth;
  32367. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  32368. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  32369. renderer.setRenderTarget( this.vsmShadowMapVertical );
  32370. _quadMesh.material = this.vsmMaterialVertical;
  32371. _quadMesh.render( renderer );
  32372. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  32373. _quadMesh.material = this.vsmMaterialHorizontal;
  32374. _quadMesh.render( renderer );
  32375. }
  32376. /**
  32377. * Frees the internal resources of this shadow node.
  32378. */
  32379. dispose() {
  32380. this._reset();
  32381. super.dispose();
  32382. }
  32383. /**
  32384. * Resets the resouce state of this shadow node.
  32385. *
  32386. * @private
  32387. */
  32388. _reset() {
  32389. this._currentShadowType = null;
  32390. disposeShadowMaterial( this.light );
  32391. if ( this.shadowMap ) {
  32392. this.shadowMap.dispose();
  32393. this.shadowMap = null;
  32394. }
  32395. if ( this.vsmShadowMapVertical !== null ) {
  32396. this.vsmShadowMapVertical.dispose();
  32397. this.vsmShadowMapVertical = null;
  32398. this.vsmMaterialVertical.dispose();
  32399. this.vsmMaterialVertical = null;
  32400. }
  32401. if ( this.vsmShadowMapHorizontal !== null ) {
  32402. this.vsmShadowMapHorizontal.dispose();
  32403. this.vsmShadowMapHorizontal = null;
  32404. this.vsmMaterialHorizontal.dispose();
  32405. this.vsmMaterialHorizontal = null;
  32406. }
  32407. }
  32408. /**
  32409. * The implementation performs the update of the shadow map if necessary.
  32410. *
  32411. * @param {NodeFrame} frame - A reference to the current node frame.
  32412. */
  32413. updateBefore( frame ) {
  32414. // do not render shadow maps during precompilation
  32415. if ( frame.renderer._isPreCompiling === true ) return;
  32416. const { shadow } = this;
  32417. let needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  32418. if ( needsUpdate ) {
  32419. if ( this._cameraFrameId.get( frame.camera ) === frame.frameId ) {
  32420. needsUpdate = false;
  32421. }
  32422. this._cameraFrameId.set( frame.camera, frame.frameId );
  32423. }
  32424. if ( needsUpdate ) {
  32425. this.updateShadow( frame );
  32426. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  32427. shadow.needsUpdate = false;
  32428. }
  32429. }
  32430. }
  32431. }
  32432. /**
  32433. * Shadow Render Object Function.
  32434. *
  32435. * @function shadowRenderObjectFunction
  32436. * @param {Object3D} object - The 3D object to render.
  32437. * @param {Scene} scene - The scene containing the object.
  32438. * @param {Camera} _camera - The camera used for rendering.
  32439. * @param {BufferGeometry} geometry - The geometry of the object.
  32440. * @param {Material} material - The material of the object.
  32441. * @param {Group} group - The group the object belongs to.
  32442. * @param {...any} params - Additional parameters for rendering.
  32443. */
  32444. /**
  32445. * TSL function for creating an instance of `ShadowNode`.
  32446. *
  32447. * @tsl
  32448. * @function
  32449. * @param {Light} light - The shadow casting light.
  32450. * @param {?LightShadow} [shadow] - The light shadow.
  32451. * @return {ShadowNode} The created shadow node.
  32452. */
  32453. const shadow = ( light, shadow ) => new ShadowNode( light, shadow );
  32454. const _clearColor$1 = /*@__PURE__*/ new Color();
  32455. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  32456. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  32457. const _lookTarget = /*@__PURE__*/ new Vector3();
  32458. // Cube map face directions and up vectors for point light shadows
  32459. // Face order: +X, -X, +Y, -Y, +Z, -Z
  32460. // WebGPU coordinate system - Y faces swapped to match texture sampling convention
  32461. const _cubeDirectionsWebGPU = [
  32462. /*@__PURE__*/ new Vector3( 1, 0, 0 ), /*@__PURE__*/ new Vector3( -1, 0, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ),
  32463. /*@__PURE__*/ new Vector3( 0, 1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, 0, -1 )
  32464. ];
  32465. const _cubeUpsWebGPU = [
  32466. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, -1 ),
  32467. /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 )
  32468. ];
  32469. // WebGL coordinate system - standard OpenGL convention
  32470. const _cubeDirectionsWebGL = [
  32471. /*@__PURE__*/ new Vector3( 1, 0, 0 ), /*@__PURE__*/ new Vector3( -1, 0, 0 ), /*@__PURE__*/ new Vector3( 0, 1, 0 ),
  32472. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, 0, -1 )
  32473. ];
  32474. const _cubeUpsWebGL = [
  32475. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ),
  32476. /*@__PURE__*/ new Vector3( 0, 0, -1 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 )
  32477. ];
  32478. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp } ) => {
  32479. return cubeTexture( depthTexture, bd3D ).compare( dp );
  32480. } );
  32481. /**
  32482. * A shadow filtering function for point lights using Vogel disk sampling and IGN.
  32483. *
  32484. * Uses 5 samples distributed via Vogel disk pattern in tangent space around the
  32485. * sample direction, rotated per-pixel using Interleaved Gradient Noise (IGN).
  32486. *
  32487. * @method
  32488. * @param {Object} inputs - The input parameter object.
  32489. * @param {CubeDepthTexture} inputs.depthTexture - A reference to the shadow cube map.
  32490. * @param {Node<vec3>} inputs.bd3D - The normalized direction from light to fragment.
  32491. * @param {Node<float>} inputs.dp - The depth value to compare against.
  32492. * @param {LightShadow} inputs.shadow - The light shadow.
  32493. * @return {Node<float>} The filtering result.
  32494. */
  32495. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, shadow } ) => {
  32496. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  32497. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  32498. const texelSize = radius.div( mapSize.x );
  32499. // Build a tangent-space coordinate system for applying offsets
  32500. const absDir = abs( bd3D );
  32501. const tangent = normalize( cross( bd3D, absDir.x.greaterThan( absDir.z ).select( vec3( 0, 1, 0 ), vec3( 1, 0, 0 ) ) ) );
  32502. const bitangent = cross( bd3D, tangent );
  32503. // Use IGN to rotate sampling pattern per pixel (phi = IGN * 2π)
  32504. const phi = interleavedGradientNoise( screenCoordinate.xy ).mul( 6.28318530718 );
  32505. // 5 samples using Vogel disk distribution in tangent space
  32506. const sample0 = vogelDiskSample( 0, 5, phi );
  32507. const sample1 = vogelDiskSample( 1, 5, phi );
  32508. const sample2 = vogelDiskSample( 2, 5, phi );
  32509. const sample3 = vogelDiskSample( 3, 5, phi );
  32510. const sample4 = vogelDiskSample( 4, 5, phi );
  32511. return cubeTexture( depthTexture, bd3D.add( tangent.mul( sample0.x ).add( bitangent.mul( sample0.y ) ).mul( texelSize ) ) ).compare( dp )
  32512. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample1.x ).add( bitangent.mul( sample1.y ) ).mul( texelSize ) ) ).compare( dp ) )
  32513. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample2.x ).add( bitangent.mul( sample2.y ) ).mul( texelSize ) ) ).compare( dp ) )
  32514. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample3.x ).add( bitangent.mul( sample3.y ) ).mul( texelSize ) ) ).compare( dp ) )
  32515. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample4.x ).add( bitangent.mul( sample4.y ) ).mul( texelSize ) ) ).compare( dp ) )
  32516. .mul( 1.0 / 5.0 );
  32517. } );
  32518. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow }, builder ) => {
  32519. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  32520. // the vector from the light to the world-space position of the fragment.
  32521. const shadowPosition = shadowCoord.xyz.toConst();
  32522. const shadowPositionAbs = shadowPosition.abs().toConst();
  32523. const viewZ = shadowPositionAbs.x.max( shadowPositionAbs.y ).max( shadowPositionAbs.z );
  32524. const shadowCameraNear = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  32525. const shadowCameraFar = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  32526. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  32527. const result = float( 1.0 ).toVar();
  32528. If( viewZ.sub( shadowCameraFar ).lessThanEqual( 0.0 ).and( viewZ.sub( shadowCameraNear ).greaterThanEqual( 0.0 ) ), () => {
  32529. let dp;
  32530. if ( builder.renderer.reversedDepthBuffer ) {
  32531. dp = viewZToReversedPerspectiveDepth( viewZ.negate(), shadowCameraNear, shadowCameraFar );
  32532. dp.subAssign( bias );
  32533. } else if ( builder.renderer.logarithmicDepthBuffer ) {
  32534. dp = viewZToLogarithmicDepth( viewZ.negate(), shadowCameraNear, shadowCameraFar );
  32535. dp.addAssign( bias );
  32536. } else {
  32537. dp = viewZToPerspectiveDepth( viewZ.negate(), shadowCameraNear, shadowCameraFar );
  32538. dp.addAssign( bias );
  32539. }
  32540. // bd3D = base direction 3D (direction from light to fragment)
  32541. const bd3D = shadowPosition.normalize();
  32542. // percentage-closer filtering using cube texture sampling
  32543. result.assign( filterFn( { depthTexture, bd3D, dp, shadow } ) );
  32544. } );
  32545. return result;
  32546. } );
  32547. /**
  32548. * Represents the shadow implementation for point light nodes.
  32549. *
  32550. * @augments ShadowNode
  32551. */
  32552. class PointShadowNode extends ShadowNode {
  32553. static get type() {
  32554. return 'PointShadowNode';
  32555. }
  32556. /**
  32557. * Constructs a new point shadow node.
  32558. *
  32559. * @param {PointLight} light - The shadow casting point light.
  32560. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  32561. */
  32562. constructor( light, shadow = null ) {
  32563. super( light, shadow );
  32564. }
  32565. /**
  32566. * Overwrites the default implementation to return point light shadow specific
  32567. * filtering functions.
  32568. *
  32569. * @param {number} type - The shadow type.
  32570. * @return {Function} The filtering function.
  32571. */
  32572. getShadowFilterFn( type ) {
  32573. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  32574. }
  32575. /**
  32576. * Overwrites the default implementation so the unaltered shadow position is used.
  32577. *
  32578. * @param {NodeBuilder} builder - A reference to the current node builder.
  32579. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  32580. * @return {Node<vec3>} The shadow coordinates.
  32581. */
  32582. setupShadowCoord( builder, shadowPosition ) {
  32583. return shadowPosition;
  32584. }
  32585. /**
  32586. * Overwrites the default implementation to only use point light specific
  32587. * shadow filter functions.
  32588. *
  32589. * @param {NodeBuilder} builder - A reference to the current node builder.
  32590. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  32591. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  32592. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's depth texture.
  32593. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  32594. * @param {LightShadow} inputs.shadow - The light shadow.
  32595. * @return {Node<float>} The result node of the shadow filtering.
  32596. */
  32597. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow } ) {
  32598. return pointShadowFilter( { filterFn, depthTexture, shadowCoord, shadow } );
  32599. }
  32600. /**
  32601. * Overwrites the default implementation to create a CubeRenderTarget with CubeDepthTexture.
  32602. *
  32603. * @param {LightShadow} shadow - The light shadow object.
  32604. * @param {NodeBuilder} builder - A reference to the current node builder.
  32605. * @return {Object} An object containing the shadow map and depth texture.
  32606. */
  32607. setupRenderTarget( shadow, builder ) {
  32608. const depthTexture = new CubeDepthTexture( shadow.mapSize.width );
  32609. depthTexture.name = 'PointShadowDepthTexture';
  32610. depthTexture.compareFunction = builder.renderer.reversedDepthBuffer ? GreaterEqualCompare : LessEqualCompare;
  32611. const shadowMap = builder.createCubeRenderTarget( shadow.mapSize.width );
  32612. shadowMap.texture.name = 'PointShadowMap';
  32613. shadowMap.depthTexture = depthTexture;
  32614. return { shadowMap, depthTexture };
  32615. }
  32616. /**
  32617. * Overwrites the default implementation with point light specific
  32618. * rendering code.
  32619. *
  32620. * @param {NodeFrame} frame - A reference to the current node frame.
  32621. */
  32622. renderShadow( frame ) {
  32623. const { shadow, shadowMap, light } = this;
  32624. const { renderer, scene } = frame;
  32625. const camera = shadow.camera;
  32626. const shadowMatrix = shadow.matrix;
  32627. // Select cube directions/ups based on coordinate system
  32628. const isWebGPU = renderer.coordinateSystem === WebGPUCoordinateSystem;
  32629. const cubeDirections = isWebGPU ? _cubeDirectionsWebGPU : _cubeDirectionsWebGL;
  32630. const cubeUps = isWebGPU ? _cubeUpsWebGPU : _cubeUpsWebGL;
  32631. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.width );
  32632. //
  32633. const previousAutoClear = renderer.autoClear;
  32634. const previousClearColor = renderer.getClearColor( _clearColor$1 );
  32635. const previousClearAlpha = renderer.getClearAlpha();
  32636. renderer.autoClear = false;
  32637. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  32638. // Render each cube face
  32639. for ( let face = 0; face < 6; face ++ ) {
  32640. // Set render target to the specific cube face
  32641. renderer.setRenderTarget( shadowMap, face );
  32642. renderer.clear();
  32643. // Update shadow camera matrices for this face
  32644. const far = light.distance || camera.far;
  32645. if ( far !== camera.far ) {
  32646. camera.far = far;
  32647. camera.updateProjectionMatrix();
  32648. }
  32649. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  32650. camera.position.copy( _lightPositionWorld );
  32651. _lookTarget.copy( camera.position );
  32652. _lookTarget.add( cubeDirections[ face ] );
  32653. camera.up.copy( cubeUps[ face ] );
  32654. camera.lookAt( _lookTarget );
  32655. camera.updateMatrixWorld();
  32656. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  32657. _projScreenMatrix$1.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  32658. shadow._frustum.setFromProjectionMatrix( _projScreenMatrix$1, camera.coordinateSystem, camera.reversedDepth );
  32659. //
  32660. const currentSceneName = scene.name;
  32661. scene.name = `Point Light Shadow [ ${ light.name || 'ID: ' + light.id } ] - Face ${ face + 1 }`;
  32662. renderer.render( scene, camera );
  32663. scene.name = currentSceneName;
  32664. }
  32665. //
  32666. renderer.autoClear = previousAutoClear;
  32667. renderer.setClearColor( previousClearColor, previousClearAlpha );
  32668. }
  32669. }
  32670. /**
  32671. * TSL function for creating an instance of `PointShadowNode`.
  32672. *
  32673. * @tsl
  32674. * @function
  32675. * @param {PointLight} light - The shadow casting point light.
  32676. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  32677. * @return {PointShadowNode} The created point shadow node.
  32678. */
  32679. const pointShadow = ( light, shadow ) => new PointShadowNode( light, shadow );
  32680. /**
  32681. * Base class for analytic light nodes.
  32682. *
  32683. * @augments LightingNode
  32684. */
  32685. class AnalyticLightNode extends LightingNode {
  32686. static get type() {
  32687. return 'AnalyticLightNode';
  32688. }
  32689. /**
  32690. * Constructs a new analytic light node.
  32691. *
  32692. * @param {?Light} [light=null] - The light source.
  32693. */
  32694. constructor( light = null ) {
  32695. super();
  32696. /**
  32697. * The light source.
  32698. *
  32699. * @type {?Light}
  32700. * @default null
  32701. */
  32702. this.light = light;
  32703. /**
  32704. * The light's color value.
  32705. *
  32706. * @type {Color}
  32707. */
  32708. this.color = new Color();
  32709. /**
  32710. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  32711. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  32712. *
  32713. * @type {Node}
  32714. */
  32715. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  32716. /**
  32717. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  32718. * The final color node is represented by a different node when using shadows.
  32719. *
  32720. * @type {?Node}
  32721. * @default null
  32722. */
  32723. this.baseColorNode = null;
  32724. /**
  32725. * Represents the light's shadow.
  32726. *
  32727. * @type {?ShadowNode}
  32728. * @default null
  32729. */
  32730. this.shadowNode = null;
  32731. /**
  32732. * Represents the light's shadow color.
  32733. *
  32734. * @type {?Node}
  32735. * @default null
  32736. */
  32737. this.shadowColorNode = null;
  32738. /**
  32739. * This flag can be used for type testing.
  32740. *
  32741. * @type {boolean}
  32742. * @readonly
  32743. * @default true
  32744. */
  32745. this.isAnalyticLightNode = true;
  32746. /**
  32747. * Overwritten since analytic light nodes are updated
  32748. * once per frame.
  32749. *
  32750. * @type {string}
  32751. * @default 'frame'
  32752. */
  32753. this.updateType = NodeUpdateType.FRAME;
  32754. if ( light && light.shadow ) {
  32755. this._shadowDisposeListener = () => {
  32756. this.disposeShadow();
  32757. };
  32758. light.addEventListener( 'dispose', this._shadowDisposeListener );
  32759. }
  32760. }
  32761. dispose() {
  32762. if ( this._shadowDisposeListener ) {
  32763. this.light.removeEventListener( 'dispose', this._shadowDisposeListener );
  32764. }
  32765. super.dispose();
  32766. }
  32767. /**
  32768. * Frees internal resources related to shadows.
  32769. */
  32770. disposeShadow() {
  32771. if ( this.shadowNode !== null ) {
  32772. this.shadowNode.dispose();
  32773. this.shadowNode = null;
  32774. }
  32775. this.shadowColorNode = null;
  32776. if ( this.baseColorNode !== null ) {
  32777. this.colorNode = this.baseColorNode;
  32778. this.baseColorNode = null;
  32779. }
  32780. }
  32781. getHash() {
  32782. return this.light.uuid;
  32783. }
  32784. /**
  32785. * Returns a node representing a direction vector which points from the current
  32786. * position in view space to the light's position in view space.
  32787. *
  32788. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  32789. * @return {Node<vec3>} The light vector node.
  32790. */
  32791. getLightVector( builder ) {
  32792. return lightViewPosition( this.light ).sub( builder.context.positionView || positionView );
  32793. }
  32794. /**
  32795. * Sets up the direct lighting for the analytic light node.
  32796. *
  32797. * @abstract
  32798. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  32799. * @return {Object|undefined} The direct light data (color and direction).
  32800. */
  32801. setupDirect( /*builder*/ ) { }
  32802. /**
  32803. * Sets up the direct rect area lighting for the analytic light node.
  32804. *
  32805. * @abstract
  32806. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  32807. * @return {Object|undefined} The direct rect area light data.
  32808. */
  32809. setupDirectRectArea( /*builder*/ ) { }
  32810. /**
  32811. * Setups the shadow node for this light. The method exists so concrete light classes
  32812. * can setup different types of shadow nodes.
  32813. *
  32814. * @return {ShadowNode} The created shadow node.
  32815. */
  32816. setupShadowNode() {
  32817. return shadow( this.light );
  32818. }
  32819. /**
  32820. * Setups the shadow for this light. This method is only executed if the light
  32821. * cast shadows and the current build object receives shadows. It incorporates
  32822. * shadows into the lighting computation.
  32823. *
  32824. * @param {NodeBuilder} builder - The current node builder.
  32825. */
  32826. setupShadow( builder ) {
  32827. const { renderer } = builder;
  32828. if ( renderer.shadowMap.enabled === false ) return;
  32829. let shadowColorNode = this.shadowColorNode;
  32830. if ( shadowColorNode === null ) {
  32831. const customShadowNode = this.light.shadow.shadowNode;
  32832. let shadowNode;
  32833. if ( customShadowNode !== undefined ) {
  32834. shadowNode = nodeObject( customShadowNode );
  32835. } else {
  32836. shadowNode = this.setupShadowNode();
  32837. }
  32838. this.shadowNode = shadowNode;
  32839. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  32840. this.baseColorNode = this.colorNode;
  32841. }
  32842. //
  32843. if ( builder.context.getShadow ) {
  32844. shadowColorNode = builder.context.getShadow( this, builder );
  32845. }
  32846. this.colorNode = shadowColorNode;
  32847. }
  32848. /**
  32849. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  32850. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  32851. * invocate the respective interface methods.
  32852. *
  32853. * @param {NodeBuilder} builder - The current node builder.
  32854. */
  32855. setup( builder ) {
  32856. this.colorNode = this.baseColorNode || this.colorNode;
  32857. if ( this.light.castShadow ) {
  32858. if ( builder.object.receiveShadow ) {
  32859. this.setupShadow( builder );
  32860. }
  32861. } else if ( this.shadowNode !== null ) {
  32862. this.shadowNode.dispose();
  32863. this.shadowNode = null;
  32864. this.shadowColorNode = null;
  32865. }
  32866. const directLightData = this.setupDirect( builder );
  32867. const directRectAreaLightData = this.setupDirectRectArea( builder );
  32868. if ( directLightData ) {
  32869. builder.lightsNode.setupDirectLight( builder, this, directLightData );
  32870. }
  32871. if ( directRectAreaLightData ) {
  32872. builder.lightsNode.setupDirectRectAreaLight( builder, this, directRectAreaLightData );
  32873. }
  32874. }
  32875. /**
  32876. * The update method is used to update light uniforms per frame.
  32877. * Potentially overwritten in concrete light nodes to update light
  32878. * specific uniforms.
  32879. *
  32880. * @param {NodeFrame} frame - A reference to the current node frame.
  32881. */
  32882. update( /*frame*/ ) {
  32883. const { light } = this;
  32884. this.color.copy( light.color ).multiplyScalar( light.intensity );
  32885. }
  32886. }
  32887. /**
  32888. * Represents a `discard` shader operation in TSL.
  32889. *
  32890. * @method
  32891. * @param {Object} inputs - The input parameter object.
  32892. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  32893. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  32894. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  32895. * @return {Node<float>} The distance falloff.
  32896. */
  32897. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( { lightDistance, cutoffDistance, decayExponent } ) => {
  32898. // based upon Frostbite 3 Moving to Physically-based Rendering
  32899. // page 32, equation 26: E[window1]
  32900. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  32901. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  32902. return cutoffDistance.greaterThan( 0 ).select(
  32903. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  32904. distanceFalloff
  32905. );
  32906. } ); // validated
  32907. const directPointLight = ( { color, lightVector, cutoffDistance, decayExponent } ) => {
  32908. const lightDirection = lightVector.normalize();
  32909. const lightDistance = lightVector.length();
  32910. const attenuation = getDistanceAttenuation( {
  32911. lightDistance,
  32912. cutoffDistance,
  32913. decayExponent
  32914. } );
  32915. const lightColor = color.mul( attenuation );
  32916. return { lightDirection, lightColor };
  32917. };
  32918. /**
  32919. * Module for representing point lights as nodes.
  32920. *
  32921. * @augments AnalyticLightNode
  32922. */
  32923. class PointLightNode extends AnalyticLightNode {
  32924. static get type() {
  32925. return 'PointLightNode';
  32926. }
  32927. /**
  32928. * Constructs a new point light node.
  32929. *
  32930. * @param {?PointLight} [light=null] - The point light source.
  32931. */
  32932. constructor( light = null ) {
  32933. super( light );
  32934. /**
  32935. * Uniform node representing the cutoff distance.
  32936. *
  32937. * @type {UniformNode<float>}
  32938. */
  32939. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  32940. /**
  32941. * Uniform node representing the decay exponent.
  32942. *
  32943. * @type {UniformNode<float>}
  32944. */
  32945. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  32946. }
  32947. /**
  32948. * Overwritten to updated point light specific uniforms.
  32949. *
  32950. * @param {NodeFrame} frame - A reference to the current node frame.
  32951. */
  32952. update( frame ) {
  32953. const { light } = this;
  32954. super.update( frame );
  32955. this.cutoffDistanceNode.value = light.distance;
  32956. this.decayExponentNode.value = light.decay;
  32957. }
  32958. /**
  32959. * Overwritten to setup point light specific shadow.
  32960. *
  32961. * @return {PointShadowNode}
  32962. */
  32963. setupShadowNode() {
  32964. return pointShadow( this.light );
  32965. }
  32966. setupDirect( builder ) {
  32967. return directPointLight( {
  32968. color: this.colorNode,
  32969. lightVector: this.getLightVector( builder ),
  32970. cutoffDistance: this.cutoffDistanceNode,
  32971. decayExponent: this.decayExponentNode
  32972. } );
  32973. }
  32974. }
  32975. /**
  32976. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  32977. *
  32978. * @tsl
  32979. * @function
  32980. * @param {Node<vec2>} coord - The uv coordinates.
  32981. * @return {Node<float>} The result data.
  32982. */
  32983. const checker = /*@__PURE__*/ Fn( ( [ coord = uv$1() ] ) => {
  32984. const uv = coord.mul( 2.0 );
  32985. const cx = uv.x.floor();
  32986. const cy = uv.y.floor();
  32987. const result = cx.add( cy ).mod( 2.0 );
  32988. return result.sign();
  32989. } );
  32990. /**
  32991. * Generates a circle based on the uv coordinates.
  32992. *
  32993. * @tsl
  32994. * @function
  32995. * @param {Node<vec2>} coord - The uv to generate the circle.
  32996. * @return {Node<float>} The circle shape.
  32997. */
  32998. const shapeCircle = Fn( ( [ coord = uv$1() ], { renderer, material } ) => {
  32999. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  33000. let alpha;
  33001. if ( material.alphaToCoverage && renderer.currentSamples > 0 ) {
  33002. const dlen = float( len2.fwidth() ).toVar();
  33003. alpha = smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus();
  33004. } else {
  33005. alpha = select( len2.greaterThan( 1.0 ), 0, 1 );
  33006. }
  33007. return alpha;
  33008. } );
  33009. // Three.js Transpiler
  33010. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  33011. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  33012. const f = float( f_immutable ).toVar();
  33013. const t = float( t_immutable ).toVar();
  33014. const b = bool( b_immutable ).toVar();
  33015. return select( b, t, f ).uniformFlow();
  33016. } ).setLayout( {
  33017. name: 'mx_select',
  33018. type: 'float',
  33019. inputs: [
  33020. { name: 'b', type: 'bool' },
  33021. { name: 't', type: 'float' },
  33022. { name: 'f', type: 'float' }
  33023. ]
  33024. } );
  33025. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  33026. const b = bool( b_immutable ).toVar();
  33027. const val = float( val_immutable ).toVar();
  33028. return select( b, val.negate(), val ).uniformFlow();
  33029. } ).setLayout( {
  33030. name: 'mx_negate_if',
  33031. type: 'float',
  33032. inputs: [
  33033. { name: 'val', type: 'float' },
  33034. { name: 'b', type: 'bool' }
  33035. ]
  33036. } );
  33037. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  33038. const x = float( x_immutable ).toVar();
  33039. return int( floor( x ) );
  33040. } ).setLayout( {
  33041. name: 'mx_floor',
  33042. type: 'int',
  33043. inputs: [
  33044. { name: 'x', type: 'float' }
  33045. ]
  33046. } );
  33047. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  33048. const x = float( x_immutable ).toVar();
  33049. i.assign( mx_floor( x ) );
  33050. return x.sub( float( i ) );
  33051. } );
  33052. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  33053. const t = float( t_immutable ).toVar();
  33054. const s = float( s_immutable ).toVar();
  33055. const v3 = float( v3_immutable ).toVar();
  33056. const v2 = float( v2_immutable ).toVar();
  33057. const v1 = float( v1_immutable ).toVar();
  33058. const v0 = float( v0_immutable ).toVar();
  33059. const s1 = float( sub( 1.0, s ) ).toVar();
  33060. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  33061. } ).setLayout( {
  33062. name: 'mx_bilerp_0',
  33063. type: 'float',
  33064. inputs: [
  33065. { name: 'v0', type: 'float' },
  33066. { name: 'v1', type: 'float' },
  33067. { name: 'v2', type: 'float' },
  33068. { name: 'v3', type: 'float' },
  33069. { name: 's', type: 'float' },
  33070. { name: 't', type: 'float' }
  33071. ]
  33072. } );
  33073. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  33074. const t = float( t_immutable ).toVar();
  33075. const s = float( s_immutable ).toVar();
  33076. const v3 = vec3( v3_immutable ).toVar();
  33077. const v2 = vec3( v2_immutable ).toVar();
  33078. const v1 = vec3( v1_immutable ).toVar();
  33079. const v0 = vec3( v0_immutable ).toVar();
  33080. const s1 = float( sub( 1.0, s ) ).toVar();
  33081. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  33082. } ).setLayout( {
  33083. name: 'mx_bilerp_1',
  33084. type: 'vec3',
  33085. inputs: [
  33086. { name: 'v0', type: 'vec3' },
  33087. { name: 'v1', type: 'vec3' },
  33088. { name: 'v2', type: 'vec3' },
  33089. { name: 'v3', type: 'vec3' },
  33090. { name: 's', type: 'float' },
  33091. { name: 't', type: 'float' }
  33092. ]
  33093. } );
  33094. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  33095. 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 ] ) => {
  33096. const r = float( r_immutable ).toVar();
  33097. const t = float( t_immutable ).toVar();
  33098. const s = float( s_immutable ).toVar();
  33099. const v7 = float( v7_immutable ).toVar();
  33100. const v6 = float( v6_immutable ).toVar();
  33101. const v5 = float( v5_immutable ).toVar();
  33102. const v4 = float( v4_immutable ).toVar();
  33103. const v3 = float( v3_immutable ).toVar();
  33104. const v2 = float( v2_immutable ).toVar();
  33105. const v1 = float( v1_immutable ).toVar();
  33106. const v0 = float( v0_immutable ).toVar();
  33107. const s1 = float( sub( 1.0, s ) ).toVar();
  33108. const t1 = float( sub( 1.0, t ) ).toVar();
  33109. const r1 = float( sub( 1.0, r ) ).toVar();
  33110. 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 ) ) ) ) ) );
  33111. } ).setLayout( {
  33112. name: 'mx_trilerp_0',
  33113. type: 'float',
  33114. inputs: [
  33115. { name: 'v0', type: 'float' },
  33116. { name: 'v1', type: 'float' },
  33117. { name: 'v2', type: 'float' },
  33118. { name: 'v3', type: 'float' },
  33119. { name: 'v4', type: 'float' },
  33120. { name: 'v5', type: 'float' },
  33121. { name: 'v6', type: 'float' },
  33122. { name: 'v7', type: 'float' },
  33123. { name: 's', type: 'float' },
  33124. { name: 't', type: 'float' },
  33125. { name: 'r', type: 'float' }
  33126. ]
  33127. } );
  33128. 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 ] ) => {
  33129. const r = float( r_immutable ).toVar();
  33130. const t = float( t_immutable ).toVar();
  33131. const s = float( s_immutable ).toVar();
  33132. const v7 = vec3( v7_immutable ).toVar();
  33133. const v6 = vec3( v6_immutable ).toVar();
  33134. const v5 = vec3( v5_immutable ).toVar();
  33135. const v4 = vec3( v4_immutable ).toVar();
  33136. const v3 = vec3( v3_immutable ).toVar();
  33137. const v2 = vec3( v2_immutable ).toVar();
  33138. const v1 = vec3( v1_immutable ).toVar();
  33139. const v0 = vec3( v0_immutable ).toVar();
  33140. const s1 = float( sub( 1.0, s ) ).toVar();
  33141. const t1 = float( sub( 1.0, t ) ).toVar();
  33142. const r1 = float( sub( 1.0, r ) ).toVar();
  33143. 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 ) ) ) ) ) );
  33144. } ).setLayout( {
  33145. name: 'mx_trilerp_1',
  33146. type: 'vec3',
  33147. inputs: [
  33148. { name: 'v0', type: 'vec3' },
  33149. { name: 'v1', type: 'vec3' },
  33150. { name: 'v2', type: 'vec3' },
  33151. { name: 'v3', type: 'vec3' },
  33152. { name: 'v4', type: 'vec3' },
  33153. { name: 'v5', type: 'vec3' },
  33154. { name: 'v6', type: 'vec3' },
  33155. { name: 'v7', type: 'vec3' },
  33156. { name: 's', type: 'float' },
  33157. { name: 't', type: 'float' },
  33158. { name: 'r', type: 'float' }
  33159. ]
  33160. } );
  33161. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  33162. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  33163. const y = float( y_immutable ).toVar();
  33164. const x = float( x_immutable ).toVar();
  33165. const hash = uint( hash_immutable ).toVar();
  33166. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  33167. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  33168. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  33169. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  33170. } ).setLayout( {
  33171. name: 'mx_gradient_float_0',
  33172. type: 'float',
  33173. inputs: [
  33174. { name: 'hash', type: 'uint' },
  33175. { name: 'x', type: 'float' },
  33176. { name: 'y', type: 'float' }
  33177. ]
  33178. } );
  33179. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  33180. const z = float( z_immutable ).toVar();
  33181. const y = float( y_immutable ).toVar();
  33182. const x = float( x_immutable ).toVar();
  33183. const hash = uint( hash_immutable ).toVar();
  33184. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  33185. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  33186. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  33187. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  33188. } ).setLayout( {
  33189. name: 'mx_gradient_float_1',
  33190. type: 'float',
  33191. inputs: [
  33192. { name: 'hash', type: 'uint' },
  33193. { name: 'x', type: 'float' },
  33194. { name: 'y', type: 'float' },
  33195. { name: 'z', type: 'float' }
  33196. ]
  33197. } );
  33198. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  33199. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  33200. const y = float( y_immutable ).toVar();
  33201. const x = float( x_immutable ).toVar();
  33202. const hash = uvec3( hash_immutable ).toVar();
  33203. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  33204. } ).setLayout( {
  33205. name: 'mx_gradient_vec3_0',
  33206. type: 'vec3',
  33207. inputs: [
  33208. { name: 'hash', type: 'uvec3' },
  33209. { name: 'x', type: 'float' },
  33210. { name: 'y', type: 'float' }
  33211. ]
  33212. } );
  33213. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  33214. const z = float( z_immutable ).toVar();
  33215. const y = float( y_immutable ).toVar();
  33216. const x = float( x_immutable ).toVar();
  33217. const hash = uvec3( hash_immutable ).toVar();
  33218. 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 ) );
  33219. } ).setLayout( {
  33220. name: 'mx_gradient_vec3_1',
  33221. type: 'vec3',
  33222. inputs: [
  33223. { name: 'hash', type: 'uvec3' },
  33224. { name: 'x', type: 'float' },
  33225. { name: 'y', type: 'float' },
  33226. { name: 'z', type: 'float' }
  33227. ]
  33228. } );
  33229. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  33230. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  33231. const v = float( v_immutable ).toVar();
  33232. return mul( 0.6616, v );
  33233. } ).setLayout( {
  33234. name: 'mx_gradient_scale2d_0',
  33235. type: 'float',
  33236. inputs: [
  33237. { name: 'v', type: 'float' }
  33238. ]
  33239. } );
  33240. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  33241. const v = float( v_immutable ).toVar();
  33242. return mul( 0.9820, v );
  33243. } ).setLayout( {
  33244. name: 'mx_gradient_scale3d_0',
  33245. type: 'float',
  33246. inputs: [
  33247. { name: 'v', type: 'float' }
  33248. ]
  33249. } );
  33250. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  33251. const v = vec3( v_immutable ).toVar();
  33252. return mul( 0.6616, v );
  33253. } ).setLayout( {
  33254. name: 'mx_gradient_scale2d_1',
  33255. type: 'vec3',
  33256. inputs: [
  33257. { name: 'v', type: 'vec3' }
  33258. ]
  33259. } );
  33260. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  33261. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  33262. const v = vec3( v_immutable ).toVar();
  33263. return mul( 0.9820, v );
  33264. } ).setLayout( {
  33265. name: 'mx_gradient_scale3d_1',
  33266. type: 'vec3',
  33267. inputs: [
  33268. { name: 'v', type: 'vec3' }
  33269. ]
  33270. } );
  33271. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  33272. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  33273. const k = int( k_immutable ).toVar();
  33274. const x = uint( x_immutable ).toVar();
  33275. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  33276. } ).setLayout( {
  33277. name: 'mx_rotl32',
  33278. type: 'uint',
  33279. inputs: [
  33280. { name: 'x', type: 'uint' },
  33281. { name: 'k', type: 'int' }
  33282. ]
  33283. } );
  33284. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  33285. a.subAssign( c );
  33286. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  33287. c.addAssign( b );
  33288. b.subAssign( a );
  33289. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  33290. a.addAssign( c );
  33291. c.subAssign( b );
  33292. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  33293. b.addAssign( a );
  33294. a.subAssign( c );
  33295. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  33296. c.addAssign( b );
  33297. b.subAssign( a );
  33298. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  33299. a.addAssign( c );
  33300. c.subAssign( b );
  33301. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  33302. b.addAssign( a );
  33303. } );
  33304. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  33305. const c = uint( c_immutable ).toVar();
  33306. const b = uint( b_immutable ).toVar();
  33307. const a = uint( a_immutable ).toVar();
  33308. c.bitXorAssign( b );
  33309. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  33310. a.bitXorAssign( c );
  33311. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  33312. b.bitXorAssign( a );
  33313. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  33314. c.bitXorAssign( b );
  33315. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  33316. a.bitXorAssign( c );
  33317. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  33318. b.bitXorAssign( a );
  33319. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  33320. c.bitXorAssign( b );
  33321. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  33322. return c;
  33323. } ).setLayout( {
  33324. name: 'mx_bjfinal',
  33325. type: 'uint',
  33326. inputs: [
  33327. { name: 'a', type: 'uint' },
  33328. { name: 'b', type: 'uint' },
  33329. { name: 'c', type: 'uint' }
  33330. ]
  33331. } );
  33332. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  33333. const bits = uint( bits_immutable ).toVar();
  33334. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  33335. } ).setLayout( {
  33336. name: 'mx_bits_to_01',
  33337. type: 'float',
  33338. inputs: [
  33339. { name: 'bits', type: 'uint' }
  33340. ]
  33341. } );
  33342. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  33343. const t = float( t_immutable ).toVar();
  33344. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  33345. } ).setLayout( {
  33346. name: 'mx_fade',
  33347. type: 'float',
  33348. inputs: [
  33349. { name: 't', type: 'float' }
  33350. ]
  33351. } );
  33352. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  33353. const x = int( x_immutable ).toVar();
  33354. const len = uint( uint( 1 ) ).toVar();
  33355. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  33356. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  33357. } ).setLayout( {
  33358. name: 'mx_hash_int_0',
  33359. type: 'uint',
  33360. inputs: [
  33361. { name: 'x', type: 'int' }
  33362. ]
  33363. } );
  33364. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  33365. const y = int( y_immutable ).toVar();
  33366. const x = int( x_immutable ).toVar();
  33367. const len = uint( uint( 2 ) ).toVar();
  33368. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  33369. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  33370. a.addAssign( uint( x ) );
  33371. b.addAssign( uint( y ) );
  33372. return mx_bjfinal( a, b, c );
  33373. } ).setLayout( {
  33374. name: 'mx_hash_int_1',
  33375. type: 'uint',
  33376. inputs: [
  33377. { name: 'x', type: 'int' },
  33378. { name: 'y', type: 'int' }
  33379. ]
  33380. } );
  33381. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  33382. const z = int( z_immutable ).toVar();
  33383. const y = int( y_immutable ).toVar();
  33384. const x = int( x_immutable ).toVar();
  33385. const len = uint( uint( 3 ) ).toVar();
  33386. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  33387. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  33388. a.addAssign( uint( x ) );
  33389. b.addAssign( uint( y ) );
  33390. c.addAssign( uint( z ) );
  33391. return mx_bjfinal( a, b, c );
  33392. } ).setLayout( {
  33393. name: 'mx_hash_int_2',
  33394. type: 'uint',
  33395. inputs: [
  33396. { name: 'x', type: 'int' },
  33397. { name: 'y', type: 'int' },
  33398. { name: 'z', type: 'int' }
  33399. ]
  33400. } );
  33401. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  33402. const xx = int( xx_immutable ).toVar();
  33403. const z = int( z_immutable ).toVar();
  33404. const y = int( y_immutable ).toVar();
  33405. const x = int( x_immutable ).toVar();
  33406. const len = uint( uint( 4 ) ).toVar();
  33407. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  33408. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  33409. a.addAssign( uint( x ) );
  33410. b.addAssign( uint( y ) );
  33411. c.addAssign( uint( z ) );
  33412. mx_bjmix( a, b, c );
  33413. a.addAssign( uint( xx ) );
  33414. return mx_bjfinal( a, b, c );
  33415. } ).setLayout( {
  33416. name: 'mx_hash_int_3',
  33417. type: 'uint',
  33418. inputs: [
  33419. { name: 'x', type: 'int' },
  33420. { name: 'y', type: 'int' },
  33421. { name: 'z', type: 'int' },
  33422. { name: 'xx', type: 'int' }
  33423. ]
  33424. } );
  33425. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  33426. const yy = int( yy_immutable ).toVar();
  33427. const xx = int( xx_immutable ).toVar();
  33428. const z = int( z_immutable ).toVar();
  33429. const y = int( y_immutable ).toVar();
  33430. const x = int( x_immutable ).toVar();
  33431. const len = uint( uint( 5 ) ).toVar();
  33432. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  33433. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  33434. a.addAssign( uint( x ) );
  33435. b.addAssign( uint( y ) );
  33436. c.addAssign( uint( z ) );
  33437. mx_bjmix( a, b, c );
  33438. a.addAssign( uint( xx ) );
  33439. b.addAssign( uint( yy ) );
  33440. return mx_bjfinal( a, b, c );
  33441. } ).setLayout( {
  33442. name: 'mx_hash_int_4',
  33443. type: 'uint',
  33444. inputs: [
  33445. { name: 'x', type: 'int' },
  33446. { name: 'y', type: 'int' },
  33447. { name: 'z', type: 'int' },
  33448. { name: 'xx', type: 'int' },
  33449. { name: 'yy', type: 'int' }
  33450. ]
  33451. } );
  33452. 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 ] );
  33453. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  33454. const y = int( y_immutable ).toVar();
  33455. const x = int( x_immutable ).toVar();
  33456. const h = uint( mx_hash_int( x, y ) ).toVar();
  33457. const result = uvec3().toVar();
  33458. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  33459. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  33460. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  33461. return result;
  33462. } ).setLayout( {
  33463. name: 'mx_hash_vec3_0',
  33464. type: 'uvec3',
  33465. inputs: [
  33466. { name: 'x', type: 'int' },
  33467. { name: 'y', type: 'int' }
  33468. ]
  33469. } );
  33470. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  33471. const z = int( z_immutable ).toVar();
  33472. const y = int( y_immutable ).toVar();
  33473. const x = int( x_immutable ).toVar();
  33474. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  33475. const result = uvec3().toVar();
  33476. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  33477. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  33478. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  33479. return result;
  33480. } ).setLayout( {
  33481. name: 'mx_hash_vec3_1',
  33482. type: 'uvec3',
  33483. inputs: [
  33484. { name: 'x', type: 'int' },
  33485. { name: 'y', type: 'int' },
  33486. { name: 'z', type: 'int' }
  33487. ]
  33488. } );
  33489. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  33490. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33491. const p = vec2( p_immutable ).toVar();
  33492. const X = int().toVar(), Y = int().toVar();
  33493. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  33494. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  33495. const u = float( mx_fade( fx ) ).toVar();
  33496. const v = float( mx_fade( fy ) ).toVar();
  33497. 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();
  33498. return mx_gradient_scale2d( result );
  33499. } ).setLayout( {
  33500. name: 'mx_perlin_noise_float_0',
  33501. type: 'float',
  33502. inputs: [
  33503. { name: 'p', type: 'vec2' }
  33504. ]
  33505. } );
  33506. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33507. const p = vec3( p_immutable ).toVar();
  33508. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  33509. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  33510. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  33511. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  33512. const u = float( mx_fade( fx ) ).toVar();
  33513. const v = float( mx_fade( fy ) ).toVar();
  33514. const w = float( mx_fade( fz ) ).toVar();
  33515. 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();
  33516. return mx_gradient_scale3d( result );
  33517. } ).setLayout( {
  33518. name: 'mx_perlin_noise_float_1',
  33519. type: 'float',
  33520. inputs: [
  33521. { name: 'p', type: 'vec3' }
  33522. ]
  33523. } );
  33524. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  33525. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33526. const p = vec2( p_immutable ).toVar();
  33527. const X = int().toVar(), Y = int().toVar();
  33528. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  33529. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  33530. const u = float( mx_fade( fx ) ).toVar();
  33531. const v = float( mx_fade( fy ) ).toVar();
  33532. 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();
  33533. return mx_gradient_scale2d( result );
  33534. } ).setLayout( {
  33535. name: 'mx_perlin_noise_vec3_0',
  33536. type: 'vec3',
  33537. inputs: [
  33538. { name: 'p', type: 'vec2' }
  33539. ]
  33540. } );
  33541. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33542. const p = vec3( p_immutable ).toVar();
  33543. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  33544. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  33545. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  33546. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  33547. const u = float( mx_fade( fx ) ).toVar();
  33548. const v = float( mx_fade( fy ) ).toVar();
  33549. const w = float( mx_fade( fz ) ).toVar();
  33550. 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();
  33551. return mx_gradient_scale3d( result );
  33552. } ).setLayout( {
  33553. name: 'mx_perlin_noise_vec3_1',
  33554. type: 'vec3',
  33555. inputs: [
  33556. { name: 'p', type: 'vec3' }
  33557. ]
  33558. } );
  33559. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  33560. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33561. const p = float( p_immutable ).toVar();
  33562. const ix = int( mx_floor( p ) ).toVar();
  33563. return mx_bits_to_01( mx_hash_int( ix ) );
  33564. } ).setLayout( {
  33565. name: 'mx_cell_noise_float_0',
  33566. type: 'float',
  33567. inputs: [
  33568. { name: 'p', type: 'float' }
  33569. ]
  33570. } );
  33571. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33572. const p = vec2( p_immutable ).toVar();
  33573. const ix = int( mx_floor( p.x ) ).toVar();
  33574. const iy = int( mx_floor( p.y ) ).toVar();
  33575. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  33576. } ).setLayout( {
  33577. name: 'mx_cell_noise_float_1',
  33578. type: 'float',
  33579. inputs: [
  33580. { name: 'p', type: 'vec2' }
  33581. ]
  33582. } );
  33583. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33584. const p = vec3( p_immutable ).toVar();
  33585. const ix = int( mx_floor( p.x ) ).toVar();
  33586. const iy = int( mx_floor( p.y ) ).toVar();
  33587. const iz = int( mx_floor( p.z ) ).toVar();
  33588. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  33589. } ).setLayout( {
  33590. name: 'mx_cell_noise_float_2',
  33591. type: 'float',
  33592. inputs: [
  33593. { name: 'p', type: 'vec3' }
  33594. ]
  33595. } );
  33596. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33597. const p = vec4( p_immutable ).toVar();
  33598. const ix = int( mx_floor( p.x ) ).toVar();
  33599. const iy = int( mx_floor( p.y ) ).toVar();
  33600. const iz = int( mx_floor( p.z ) ).toVar();
  33601. const iw = int( mx_floor( p.w ) ).toVar();
  33602. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  33603. } ).setLayout( {
  33604. name: 'mx_cell_noise_float_3',
  33605. type: 'float',
  33606. inputs: [
  33607. { name: 'p', type: 'vec4' }
  33608. ]
  33609. } );
  33610. 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 ] );
  33611. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33612. const p = float( p_immutable ).toVar();
  33613. const ix = int( mx_floor( p ) ).toVar();
  33614. 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 ) ) ) );
  33615. } ).setLayout( {
  33616. name: 'mx_cell_noise_vec3_0',
  33617. type: 'vec3',
  33618. inputs: [
  33619. { name: 'p', type: 'float' }
  33620. ]
  33621. } );
  33622. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33623. const p = vec2( p_immutable ).toVar();
  33624. const ix = int( mx_floor( p.x ) ).toVar();
  33625. const iy = int( mx_floor( p.y ) ).toVar();
  33626. 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 ) ) ) );
  33627. } ).setLayout( {
  33628. name: 'mx_cell_noise_vec3_1',
  33629. type: 'vec3',
  33630. inputs: [
  33631. { name: 'p', type: 'vec2' }
  33632. ]
  33633. } );
  33634. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33635. const p = vec3( p_immutable ).toVar();
  33636. const ix = int( mx_floor( p.x ) ).toVar();
  33637. const iy = int( mx_floor( p.y ) ).toVar();
  33638. const iz = int( mx_floor( p.z ) ).toVar();
  33639. 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 ) ) ) );
  33640. } ).setLayout( {
  33641. name: 'mx_cell_noise_vec3_2',
  33642. type: 'vec3',
  33643. inputs: [
  33644. { name: 'p', type: 'vec3' }
  33645. ]
  33646. } );
  33647. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33648. const p = vec4( p_immutable ).toVar();
  33649. const ix = int( mx_floor( p.x ) ).toVar();
  33650. const iy = int( mx_floor( p.y ) ).toVar();
  33651. const iz = int( mx_floor( p.z ) ).toVar();
  33652. const iw = int( mx_floor( p.w ) ).toVar();
  33653. 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 ) ) ) );
  33654. } ).setLayout( {
  33655. name: 'mx_cell_noise_vec3_3',
  33656. type: 'vec3',
  33657. inputs: [
  33658. { name: 'p', type: 'vec4' }
  33659. ]
  33660. } );
  33661. 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 ] );
  33662. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  33663. const diminish = float( diminish_immutable ).toVar();
  33664. const lacunarity = float( lacunarity_immutable ).toVar();
  33665. const octaves = int( octaves_immutable ).toVar();
  33666. const p = vec3( p_immutable ).toVar();
  33667. const result = float( 0.0 ).toVar();
  33668. const amplitude = float( 1.0 ).toVar();
  33669. Loop( octaves, () => {
  33670. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  33671. amplitude.mulAssign( diminish );
  33672. p.mulAssign( lacunarity );
  33673. } );
  33674. return result;
  33675. } ).setLayout( {
  33676. name: 'mx_fractal_noise_float',
  33677. type: 'float',
  33678. inputs: [
  33679. { name: 'p', type: 'vec3' },
  33680. { name: 'octaves', type: 'int' },
  33681. { name: 'lacunarity', type: 'float' },
  33682. { name: 'diminish', type: 'float' }
  33683. ]
  33684. } );
  33685. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  33686. const diminish = float( diminish_immutable ).toVar();
  33687. const lacunarity = float( lacunarity_immutable ).toVar();
  33688. const octaves = int( octaves_immutable ).toVar();
  33689. const p = vec3( p_immutable ).toVar();
  33690. const result = vec3( 0.0 ).toVar();
  33691. const amplitude = float( 1.0 ).toVar();
  33692. Loop( octaves, () => {
  33693. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  33694. amplitude.mulAssign( diminish );
  33695. p.mulAssign( lacunarity );
  33696. } );
  33697. return result;
  33698. } ).setLayout( {
  33699. name: 'mx_fractal_noise_vec3',
  33700. type: 'vec3',
  33701. inputs: [
  33702. { name: 'p', type: 'vec3' },
  33703. { name: 'octaves', type: 'int' },
  33704. { name: 'lacunarity', type: 'float' },
  33705. { name: 'diminish', type: 'float' }
  33706. ]
  33707. } );
  33708. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  33709. const diminish = float( diminish_immutable ).toVar();
  33710. const lacunarity = float( lacunarity_immutable ).toVar();
  33711. const octaves = int( octaves_immutable ).toVar();
  33712. const p = vec3( p_immutable ).toVar();
  33713. 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 ) );
  33714. } ).setLayout( {
  33715. name: 'mx_fractal_noise_vec2',
  33716. type: 'vec2',
  33717. inputs: [
  33718. { name: 'p', type: 'vec3' },
  33719. { name: 'octaves', type: 'int' },
  33720. { name: 'lacunarity', type: 'float' },
  33721. { name: 'diminish', type: 'float' }
  33722. ]
  33723. } );
  33724. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  33725. const diminish = float( diminish_immutable ).toVar();
  33726. const lacunarity = float( lacunarity_immutable ).toVar();
  33727. const octaves = int( octaves_immutable ).toVar();
  33728. const p = vec3( p_immutable ).toVar();
  33729. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  33730. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  33731. return vec4( c, f );
  33732. } ).setLayout( {
  33733. name: 'mx_fractal_noise_vec4',
  33734. type: 'vec4',
  33735. inputs: [
  33736. { name: 'p', type: 'vec3' },
  33737. { name: 'octaves', type: 'int' },
  33738. { name: 'lacunarity', type: 'float' },
  33739. { name: 'diminish', type: 'float' }
  33740. ]
  33741. } );
  33742. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  33743. const metric = int( metric_immutable ).toVar();
  33744. const jitter = float( jitter_immutable ).toVar();
  33745. const yoff = int( yoff_immutable ).toVar();
  33746. const xoff = int( xoff_immutable ).toVar();
  33747. const y = int( y_immutable ).toVar();
  33748. const x = int( x_immutable ).toVar();
  33749. const p = vec2( p_immutable ).toVar();
  33750. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  33751. const off = vec2( tmp.x, tmp.y ).toVar();
  33752. off.subAssign( 0.5 );
  33753. off.mulAssign( jitter );
  33754. off.addAssign( 0.5 );
  33755. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  33756. const diff = vec2( cellpos.sub( p ) ).toVar();
  33757. If( metric.equal( int( 2 ) ), () => {
  33758. return abs( diff.x ).add( abs( diff.y ) );
  33759. } );
  33760. If( metric.equal( int( 3 ) ), () => {
  33761. return max$1( abs( diff.x ), abs( diff.y ) );
  33762. } );
  33763. return dot( diff, diff );
  33764. } ).setLayout( {
  33765. name: 'mx_worley_distance_0',
  33766. type: 'float',
  33767. inputs: [
  33768. { name: 'p', type: 'vec2' },
  33769. { name: 'x', type: 'int' },
  33770. { name: 'y', type: 'int' },
  33771. { name: 'xoff', type: 'int' },
  33772. { name: 'yoff', type: 'int' },
  33773. { name: 'jitter', type: 'float' },
  33774. { name: 'metric', type: 'int' }
  33775. ]
  33776. } );
  33777. 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 ] ) => {
  33778. const metric = int( metric_immutable ).toVar();
  33779. const jitter = float( jitter_immutable ).toVar();
  33780. const zoff = int( zoff_immutable ).toVar();
  33781. const yoff = int( yoff_immutable ).toVar();
  33782. const xoff = int( xoff_immutable ).toVar();
  33783. const z = int( z_immutable ).toVar();
  33784. const y = int( y_immutable ).toVar();
  33785. const x = int( x_immutable ).toVar();
  33786. const p = vec3( p_immutable ).toVar();
  33787. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  33788. off.subAssign( 0.5 );
  33789. off.mulAssign( jitter );
  33790. off.addAssign( 0.5 );
  33791. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  33792. const diff = vec3( cellpos.sub( p ) ).toVar();
  33793. If( metric.equal( int( 2 ) ), () => {
  33794. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  33795. } );
  33796. If( metric.equal( int( 3 ) ), () => {
  33797. return max$1( abs( diff.x ), abs( diff.y ), abs( diff.z ) );
  33798. } );
  33799. return dot( diff, diff );
  33800. } ).setLayout( {
  33801. name: 'mx_worley_distance_1',
  33802. type: 'float',
  33803. inputs: [
  33804. { name: 'p', type: 'vec3' },
  33805. { name: 'x', type: 'int' },
  33806. { name: 'y', type: 'int' },
  33807. { name: 'z', type: 'int' },
  33808. { name: 'xoff', type: 'int' },
  33809. { name: 'yoff', type: 'int' },
  33810. { name: 'zoff', type: 'int' },
  33811. { name: 'jitter', type: 'float' },
  33812. { name: 'metric', type: 'int' }
  33813. ]
  33814. } );
  33815. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  33816. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33817. const metric = int( metric_immutable ).toVar();
  33818. const jitter = float( jitter_immutable ).toVar();
  33819. const p = vec2( p_immutable ).toVar();
  33820. const X = int().toVar(), Y = int().toVar();
  33821. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  33822. const sqdist = float( 1e6 ).toVar();
  33823. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33824. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33825. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  33826. sqdist.assign( min$1( sqdist, dist ) );
  33827. } );
  33828. } );
  33829. If( metric.equal( int( 0 ) ), () => {
  33830. sqdist.assign( sqrt( sqdist ) );
  33831. } );
  33832. return sqdist;
  33833. } ).setLayout( {
  33834. name: 'mx_worley_noise_float_0',
  33835. type: 'float',
  33836. inputs: [
  33837. { name: 'p', type: 'vec2' },
  33838. { name: 'jitter', type: 'float' },
  33839. { name: 'metric', type: 'int' }
  33840. ]
  33841. } );
  33842. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33843. const metric = int( metric_immutable ).toVar();
  33844. const jitter = float( jitter_immutable ).toVar();
  33845. const p = vec2( p_immutable ).toVar();
  33846. const X = int().toVar(), Y = int().toVar();
  33847. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  33848. const sqdist = vec2( 1e6, 1e6 ).toVar();
  33849. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33850. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33851. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  33852. If( dist.lessThan( sqdist.x ), () => {
  33853. sqdist.y.assign( sqdist.x );
  33854. sqdist.x.assign( dist );
  33855. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  33856. sqdist.y.assign( dist );
  33857. } );
  33858. } );
  33859. } );
  33860. If( metric.equal( int( 0 ) ), () => {
  33861. sqdist.assign( sqrt( sqdist ) );
  33862. } );
  33863. return sqdist;
  33864. } ).setLayout( {
  33865. name: 'mx_worley_noise_vec2_0',
  33866. type: 'vec2',
  33867. inputs: [
  33868. { name: 'p', type: 'vec2' },
  33869. { name: 'jitter', type: 'float' },
  33870. { name: 'metric', type: 'int' }
  33871. ]
  33872. } );
  33873. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33874. const metric = int( metric_immutable ).toVar();
  33875. const jitter = float( jitter_immutable ).toVar();
  33876. const p = vec2( p_immutable ).toVar();
  33877. const X = int().toVar(), Y = int().toVar();
  33878. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  33879. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  33880. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33881. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33882. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  33883. If( dist.lessThan( sqdist.x ), () => {
  33884. sqdist.z.assign( sqdist.y );
  33885. sqdist.y.assign( sqdist.x );
  33886. sqdist.x.assign( dist );
  33887. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  33888. sqdist.z.assign( sqdist.y );
  33889. sqdist.y.assign( dist );
  33890. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  33891. sqdist.z.assign( dist );
  33892. } );
  33893. } );
  33894. } );
  33895. If( metric.equal( int( 0 ) ), () => {
  33896. sqdist.assign( sqrt( sqdist ) );
  33897. } );
  33898. return sqdist;
  33899. } ).setLayout( {
  33900. name: 'mx_worley_noise_vec3_0',
  33901. type: 'vec3',
  33902. inputs: [
  33903. { name: 'p', type: 'vec2' },
  33904. { name: 'jitter', type: 'float' },
  33905. { name: 'metric', type: 'int' }
  33906. ]
  33907. } );
  33908. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33909. const metric = int( metric_immutable ).toVar();
  33910. const jitter = float( jitter_immutable ).toVar();
  33911. const p = vec3( p_immutable ).toVar();
  33912. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  33913. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  33914. const sqdist = float( 1e6 ).toVar();
  33915. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33916. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33917. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  33918. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  33919. sqdist.assign( min$1( sqdist, dist ) );
  33920. } );
  33921. } );
  33922. } );
  33923. If( metric.equal( int( 0 ) ), () => {
  33924. sqdist.assign( sqrt( sqdist ) );
  33925. } );
  33926. return sqdist;
  33927. } ).setLayout( {
  33928. name: 'mx_worley_noise_float_1',
  33929. type: 'float',
  33930. inputs: [
  33931. { name: 'p', type: 'vec3' },
  33932. { name: 'jitter', type: 'float' },
  33933. { name: 'metric', type: 'int' }
  33934. ]
  33935. } );
  33936. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  33937. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33938. const metric = int( metric_immutable ).toVar();
  33939. const jitter = float( jitter_immutable ).toVar();
  33940. const p = vec3( p_immutable ).toVar();
  33941. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  33942. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  33943. const sqdist = vec2( 1e6, 1e6 ).toVar();
  33944. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33945. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33946. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  33947. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  33948. If( dist.lessThan( sqdist.x ), () => {
  33949. sqdist.y.assign( sqdist.x );
  33950. sqdist.x.assign( dist );
  33951. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  33952. sqdist.y.assign( dist );
  33953. } );
  33954. } );
  33955. } );
  33956. } );
  33957. If( metric.equal( int( 0 ) ), () => {
  33958. sqdist.assign( sqrt( sqdist ) );
  33959. } );
  33960. return sqdist;
  33961. } ).setLayout( {
  33962. name: 'mx_worley_noise_vec2_1',
  33963. type: 'vec2',
  33964. inputs: [
  33965. { name: 'p', type: 'vec3' },
  33966. { name: 'jitter', type: 'float' },
  33967. { name: 'metric', type: 'int' }
  33968. ]
  33969. } );
  33970. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  33971. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33972. const metric = int( metric_immutable ).toVar();
  33973. const jitter = float( jitter_immutable ).toVar();
  33974. const p = vec3( p_immutable ).toVar();
  33975. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  33976. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  33977. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  33978. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33979. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33980. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  33981. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  33982. If( dist.lessThan( sqdist.x ), () => {
  33983. sqdist.z.assign( sqdist.y );
  33984. sqdist.y.assign( sqdist.x );
  33985. sqdist.x.assign( dist );
  33986. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  33987. sqdist.z.assign( sqdist.y );
  33988. sqdist.y.assign( dist );
  33989. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  33990. sqdist.z.assign( dist );
  33991. } );
  33992. } );
  33993. } );
  33994. } );
  33995. If( metric.equal( int( 0 ) ), () => {
  33996. sqdist.assign( sqrt( sqdist ) );
  33997. } );
  33998. return sqdist;
  33999. } ).setLayout( {
  34000. name: 'mx_worley_noise_vec3_1',
  34001. type: 'vec3',
  34002. inputs: [
  34003. { name: 'p', type: 'vec3' },
  34004. { name: 'jitter', type: 'float' },
  34005. { name: 'metric', type: 'int' }
  34006. ]
  34007. } );
  34008. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  34009. // Unified Noise 2D
  34010. const mx_unifiednoise2d$1 = /*@__PURE__*/ Fn( ( [
  34011. noiseType_immutable, texcoord_immutable, freq_immutable, offset_immutable,
  34012. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  34013. octaves_immutable, lacunarity_immutable, diminish_immutable
  34014. ] ) => {
  34015. const noiseType = int( noiseType_immutable ).toVar();
  34016. const texcoord = vec2( texcoord_immutable ).toVar();
  34017. const freq = vec2( freq_immutable ).toVar();
  34018. const offset = vec2( offset_immutable ).toVar();
  34019. const jitter = float( jitter_immutable ).toVar();
  34020. const outmin = float( outmin_immutable ).toVar();
  34021. const outmax = float( outmax_immutable ).toVar();
  34022. const clampoutput = bool( clampoutput_immutable ).toVar();
  34023. const octaves = int( octaves_immutable ).toVar();
  34024. const lacunarity = float( lacunarity_immutable ).toVar();
  34025. const diminish = float( diminish_immutable ).toVar();
  34026. // Compute input position
  34027. const p = texcoord.mul( freq ).add( offset );
  34028. const result = float( 0.0 ).toVar();
  34029. // Perlin
  34030. If( noiseType.equal( int( 0 ) ), () => {
  34031. result.assign( mx_perlin_noise_vec3( p ) );
  34032. } );
  34033. // Cell
  34034. If( noiseType.equal( int( 1 ) ), () => {
  34035. result.assign( mx_cell_noise_vec3( p ) );
  34036. } );
  34037. // Worley (metric=0 = euclidean)
  34038. If( noiseType.equal( int( 2 ) ), () => {
  34039. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  34040. } );
  34041. // Fractal (use vec3(p, 0.0) for 2D input)
  34042. If( noiseType.equal( int( 3 ) ), () => {
  34043. result.assign( mx_fractal_noise_vec3$1( vec3( p, 0.0 ), octaves, lacunarity, diminish ) );
  34044. } );
  34045. // Remap output to [outmin, outmax]
  34046. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  34047. // Clamp if requested
  34048. If( clampoutput, () => {
  34049. result.assign( clamp( result, outmin, outmax ) );
  34050. } );
  34051. return result;
  34052. } ).setLayout( {
  34053. name: 'mx_unifiednoise2d',
  34054. type: 'float',
  34055. inputs: [
  34056. { name: 'noiseType', type: 'int' },
  34057. { name: 'texcoord', type: 'vec2' },
  34058. { name: 'freq', type: 'vec2' },
  34059. { name: 'offset', type: 'vec2' },
  34060. { name: 'jitter', type: 'float' },
  34061. { name: 'outmin', type: 'float' },
  34062. { name: 'outmax', type: 'float' },
  34063. { name: 'clampoutput', type: 'bool' },
  34064. { name: 'octaves', type: 'int' },
  34065. { name: 'lacunarity', type: 'float' },
  34066. { name: 'diminish', type: 'float' }
  34067. ]
  34068. } );
  34069. // Unified Noise 3D
  34070. const mx_unifiednoise3d$1 = /*@__PURE__*/ Fn( ( [
  34071. noiseType_immutable, position_immutable, freq_immutable, offset_immutable,
  34072. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  34073. octaves_immutable, lacunarity_immutable, diminish_immutable
  34074. ] ) => {
  34075. const noiseType = int( noiseType_immutable ).toVar();
  34076. const position = vec3( position_immutable ).toVar();
  34077. const freq = vec3( freq_immutable ).toVar();
  34078. const offset = vec3( offset_immutable ).toVar();
  34079. const jitter = float( jitter_immutable ).toVar();
  34080. const outmin = float( outmin_immutable ).toVar();
  34081. const outmax = float( outmax_immutable ).toVar();
  34082. const clampoutput = bool( clampoutput_immutable ).toVar();
  34083. const octaves = int( octaves_immutable ).toVar();
  34084. const lacunarity = float( lacunarity_immutable ).toVar();
  34085. const diminish = float( diminish_immutable ).toVar();
  34086. // Compute input position
  34087. const p = position.mul( freq ).add( offset );
  34088. const result = float( 0.0 ).toVar();
  34089. // Perlin
  34090. If( noiseType.equal( int( 0 ) ), () => {
  34091. result.assign( mx_perlin_noise_vec3( p ) );
  34092. } );
  34093. // Cell
  34094. If( noiseType.equal( int( 1 ) ), () => {
  34095. result.assign( mx_cell_noise_vec3( p ) );
  34096. } );
  34097. // Worley (metric=0 = euclidean)
  34098. If( noiseType.equal( int( 2 ) ), () => {
  34099. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  34100. } );
  34101. // Fractal
  34102. If( noiseType.equal( int( 3 ) ), () => {
  34103. result.assign( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) );
  34104. } );
  34105. // Remap output to [outmin, outmax]
  34106. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  34107. // Clamp if requested
  34108. If( clampoutput, () => {
  34109. result.assign( clamp( result, outmin, outmax ) );
  34110. } );
  34111. return result;
  34112. } ).setLayout( {
  34113. name: 'mx_unifiednoise3d',
  34114. type: 'float',
  34115. inputs: [
  34116. { name: 'noiseType', type: 'int' },
  34117. { name: 'position', type: 'vec3' },
  34118. { name: 'freq', type: 'vec3' },
  34119. { name: 'offset', type: 'vec3' },
  34120. { name: 'jitter', type: 'float' },
  34121. { name: 'outmin', type: 'float' },
  34122. { name: 'outmax', type: 'float' },
  34123. { name: 'clampoutput', type: 'bool' },
  34124. { name: 'octaves', type: 'int' },
  34125. { name: 'lacunarity', type: 'float' },
  34126. { name: 'diminish', type: 'float' }
  34127. ]
  34128. } );
  34129. // Three.js Transpiler
  34130. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  34131. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  34132. const s = hsv.y;
  34133. const v = hsv.z;
  34134. const result = vec3().toVar();
  34135. If( s.lessThan( 0.0001 ), () => {
  34136. result.assign( vec3( v, v, v ) );
  34137. } ).Else( () => {
  34138. let h = hsv.x;
  34139. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  34140. const hi = int( trunc( h ) );
  34141. const f = h.sub( float( hi ) );
  34142. const p = v.mul( s.oneMinus() );
  34143. const q = v.mul( s.mul( f ).oneMinus() );
  34144. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  34145. If( hi.equal( int( 0 ) ), () => {
  34146. result.assign( vec3( v, t, p ) );
  34147. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  34148. result.assign( vec3( q, v, p ) );
  34149. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  34150. result.assign( vec3( p, v, t ) );
  34151. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  34152. result.assign( vec3( p, q, v ) );
  34153. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  34154. result.assign( vec3( t, p, v ) );
  34155. } ).Else( () => {
  34156. result.assign( vec3( v, p, q ) );
  34157. } );
  34158. } );
  34159. return result;
  34160. } ).setLayout( {
  34161. name: 'mx_hsvtorgb',
  34162. type: 'vec3',
  34163. inputs: [
  34164. { name: 'hsv', type: 'vec3' }
  34165. ]
  34166. } );
  34167. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  34168. const c = vec3( c_immutable ).toVar();
  34169. const r = float( c.x ).toVar();
  34170. const g = float( c.y ).toVar();
  34171. const b = float( c.z ).toVar();
  34172. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  34173. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  34174. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  34175. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  34176. v.assign( maxcomp );
  34177. If( maxcomp.greaterThan( 0.0 ), () => {
  34178. s.assign( delta.div( maxcomp ) );
  34179. } ).Else( () => {
  34180. s.assign( 0.0 );
  34181. } );
  34182. If( s.lessThanEqual( 0.0 ), () => {
  34183. h.assign( 0.0 );
  34184. } ).Else( () => {
  34185. If( r.greaterThanEqual( maxcomp ), () => {
  34186. h.assign( g.sub( b ).div( delta ) );
  34187. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  34188. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  34189. } ).Else( () => {
  34190. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  34191. } );
  34192. h.mulAssign( 1.0 / 6.0 );
  34193. If( h.lessThan( 0.0 ), () => {
  34194. h.addAssign( 1.0 );
  34195. } );
  34196. } );
  34197. return vec3( h, s, v );
  34198. } ).setLayout( {
  34199. name: 'mx_rgbtohsv',
  34200. type: 'vec3',
  34201. inputs: [
  34202. { name: 'c', type: 'vec3' }
  34203. ]
  34204. } );
  34205. // Three.js Transpiler
  34206. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  34207. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  34208. const color = vec3( color_immutable ).toVar();
  34209. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  34210. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  34211. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  34212. return mix( linSeg, powSeg, isAbove );
  34213. } ).setLayout( {
  34214. name: 'mx_srgb_texture_to_lin_rec709',
  34215. type: 'vec3',
  34216. inputs: [
  34217. { name: 'color', type: 'vec3' }
  34218. ]
  34219. } );
  34220. const mx_aastep = ( threshold, value ) => {
  34221. threshold = float( threshold );
  34222. value = float( value );
  34223. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  34224. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  34225. };
  34226. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  34227. const mx_ramplr = ( valuel, valuer, texcoord = uv$1() ) => _ramp( valuel, valuer, texcoord, 'x' );
  34228. const mx_ramptb = ( valuet, valueb, texcoord = uv$1() ) => _ramp( valuet, valueb, texcoord, 'y' );
  34229. // Bilinear ramp: interpolate between four corners (tl, tr, bl, br) using texcoord.x and texcoord.y
  34230. const mx_ramp4 = (
  34231. valuetl, valuetr, valuebl, valuebr, texcoord = uv$1()
  34232. ) => {
  34233. const u = texcoord.x.clamp();
  34234. const v = texcoord.y.clamp();
  34235. const top = mix( valuetl, valuetr, u );
  34236. const bottom = mix( valuebl, valuebr, u );
  34237. return mix( top, bottom, v );
  34238. };
  34239. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  34240. const mx_splitlr = ( valuel, valuer, center, texcoord = uv$1() ) => _split( valuel, valuer, center, texcoord, 'x' );
  34241. const mx_splittb = ( valuet, valueb, center, texcoord = uv$1() ) => _split( valuet, valueb, center, texcoord, 'y' );
  34242. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv$1() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  34243. const mx_safepower = ( in1, in2 = 1 ) => {
  34244. in1 = float( in1 );
  34245. return in1.abs().pow( in2 ).mul( in1.sign() );
  34246. };
  34247. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  34248. const mx_noise_float = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  34249. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  34250. const mx_noise_vec3 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  34251. const mx_noise_vec4 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => {
  34252. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  34253. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  34254. return noise_vec4.mul( amplitude ).add( pivot );
  34255. };
  34256. const mx_unifiednoise2d = ( noiseType, texcoord = uv$1(), freq = vec2( 1, 1 ), offset = vec2( 0, 0 ), jitter = 1, outmin = 0, outmax = 1, clampoutput = false, octaves = 1, lacunarity = 2, diminish = .5 ) => mx_unifiednoise2d$1( noiseType, texcoord.convert( 'vec2|vec3' ), freq, offset, jitter, outmin, outmax, clampoutput, octaves, lacunarity, diminish );
  34257. const mx_unifiednoise3d = ( noiseType, texcoord = uv$1(), freq = vec2( 1, 1 ), offset = vec2( 0, 0 ), jitter = 1, outmin = 0, outmax = 1, clampoutput = false, octaves = 1, lacunarity = 2, diminish = .5 ) => mx_unifiednoise3d$1( noiseType, texcoord.convert( 'vec2|vec3' ), freq, offset, jitter, outmin, outmax, clampoutput, octaves, lacunarity, diminish );
  34258. const mx_worley_noise_float = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  34259. const mx_worley_noise_vec2 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  34260. const mx_worley_noise_vec3 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  34261. const mx_cell_noise_float = ( texcoord = uv$1() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  34262. const mx_fractal_noise_float = ( position = uv$1(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_float$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  34263. const mx_fractal_noise_vec2 = ( position = uv$1(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec2$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  34264. const mx_fractal_noise_vec3 = ( position = uv$1(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec3$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  34265. const mx_fractal_noise_vec4 = ( position = uv$1(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec4$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  34266. // === Moved from MaterialXLoader.js ===
  34267. // Math ops
  34268. const mx_add = ( in1, in2 = float( 0 ) ) => add( in1, in2 );
  34269. const mx_subtract = ( in1, in2 = float( 0 ) ) => sub( in1, in2 );
  34270. const mx_multiply = ( in1, in2 = float( 1 ) ) => mul( in1, in2 );
  34271. const mx_divide = ( in1, in2 = float( 1 ) ) => div( in1, in2 );
  34272. const mx_modulo = ( in1, in2 = float( 1 ) ) => mod( in1, in2 );
  34273. const mx_power = ( in1, in2 = float( 1 ) ) => pow( in1, in2 );
  34274. const mx_atan2 = ( in1 = float( 0 ), in2 = float( 1 ) ) => atan( in1, in2 );
  34275. const mx_timer = () => time;
  34276. const mx_frame = () => frameId;
  34277. const mx_invert = ( in1, amount = float( 1 ) ) => sub( amount, in1 );
  34278. const mx_ifgreater = ( value1, value2, in1, in2 ) => value1.greaterThan( value2 ).mix( in1, in2 );
  34279. const mx_ifgreatereq = ( value1, value2, in1, in2 ) => value1.greaterThanEqual( value2 ).mix( in1, in2 );
  34280. const mx_ifequal = ( value1, value2, in1, in2 ) => value1.equal( value2 ).mix( in1, in2 );
  34281. // Enhanced separate node to support multi-output referencing (outx, outy, outz, outw)
  34282. const mx_separate = ( in1, channelOrOut = null ) => {
  34283. if ( typeof channelOrOut === 'string' ) {
  34284. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  34285. const c = channelOrOut.replace( /^out/, '' ).toLowerCase();
  34286. if ( map[ c ] !== undefined ) return in1.element( map[ c ] );
  34287. }
  34288. if ( typeof channelOrOut === 'number' ) {
  34289. return in1.element( channelOrOut );
  34290. }
  34291. if ( typeof channelOrOut === 'string' && channelOrOut.length === 1 ) {
  34292. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  34293. if ( map[ channelOrOut ] !== undefined ) return in1.element( map[ channelOrOut ] );
  34294. }
  34295. return in1;
  34296. };
  34297. const mx_place2d = (
  34298. texcoord, pivot = vec2( 0.5, 0.5 ), scale = vec2( 1, 1 ), rotate = float( 0 ), offset = vec2( 0, 0 )/*, operationorder = int( 0 )*/
  34299. ) => {
  34300. let uv = texcoord;
  34301. if ( pivot ) uv = uv.sub( pivot );
  34302. if ( scale ) uv = uv.mul( scale );
  34303. if ( rotate ) {
  34304. const rad = rotate.mul( Math.PI / 180.0 );
  34305. const cosR = rad.cos();
  34306. const sinR = rad.sin();
  34307. uv = vec2(
  34308. uv.x.mul( cosR ).sub( uv.y.mul( sinR ) ),
  34309. uv.x.mul( sinR ).add( uv.y.mul( cosR ) )
  34310. );
  34311. }
  34312. if ( pivot ) uv = uv.add( pivot );
  34313. if ( offset ) uv = uv.add( offset );
  34314. return uv;
  34315. };
  34316. const mx_rotate2d = ( input, amount ) => {
  34317. input = vec2( input );
  34318. amount = float( amount );
  34319. const radians = amount.mul( Math.PI / 180.0 );
  34320. return rotate( input, radians );
  34321. };
  34322. const mx_rotate3d = ( input, amount, axis ) => {
  34323. input = vec3( input );
  34324. amount = float( amount );
  34325. axis = vec3( axis );
  34326. const radians = amount.mul( Math.PI / 180.0 );
  34327. const nAxis = axis.normalize();
  34328. const cosA = radians.cos();
  34329. const sinA = radians.sin();
  34330. const oneMinusCosA = float( 1 ).sub( cosA );
  34331. const rot =
  34332. input.mul( cosA )
  34333. .add( nAxis.cross( input ).mul( sinA ) )
  34334. .add( nAxis.mul( nAxis.dot( input ) ).mul( oneMinusCosA ) );
  34335. return rot;
  34336. };
  34337. const mx_heighttonormal = ( input, scale/*, texcoord*/ ) => {
  34338. input = vec3( input );
  34339. scale = float( scale );
  34340. return bumpMap( input, scale );
  34341. };
  34342. /**
  34343. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  34344. *
  34345. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  34346. *
  34347. * ```js
  34348. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  34349. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  34350. * ```
  34351. *
  34352. * @tsl
  34353. * @function
  34354. * @param {Node<vec3>} normal - The normal to correct.
  34355. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  34356. * @param {Node<vec3>} cubePos - The cube position.
  34357. * @return {Node<vec3>} The parallax corrected normal.
  34358. */
  34359. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  34360. const nDir = normalize( normal ).toVar();
  34361. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  34362. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  34363. const rbminmax = vec3().toVar();
  34364. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  34365. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  34366. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  34367. const correction = min$1( rbminmax.x, rbminmax.y, rbminmax.z ).toVar();
  34368. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar();
  34369. return boxIntersection.sub( cubePos );
  34370. } );
  34371. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  34372. // normal is assumed to have unit length
  34373. const x = normal.x, y = normal.y, z = normal.z;
  34374. // band 0
  34375. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  34376. // band 1
  34377. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  34378. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  34379. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  34380. // band 2
  34381. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  34382. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  34383. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  34384. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  34385. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  34386. return result;
  34387. } );
  34388. // constants
  34389. var TSL = /*#__PURE__*/Object.freeze({
  34390. __proto__: null,
  34391. BRDF_GGX: BRDF_GGX,
  34392. BRDF_Lambert: BRDF_Lambert,
  34393. BasicPointShadowFilter: BasicPointShadowFilter,
  34394. BasicShadowFilter: BasicShadowFilter,
  34395. Break: Break,
  34396. Const: Const,
  34397. Continue: Continue,
  34398. DFGLUT: DFGLUT,
  34399. D_GGX: D_GGX,
  34400. Discard: Discard,
  34401. EPSILON: EPSILON,
  34402. F_Schlick: F_Schlick,
  34403. Fn: Fn,
  34404. HALF_PI: HALF_PI,
  34405. INFINITY: INFINITY,
  34406. If: If,
  34407. Loop: Loop,
  34408. NodeAccess: NodeAccess,
  34409. NodeShaderStage: NodeShaderStage,
  34410. NodeType: NodeType,
  34411. NodeUpdateType: NodeUpdateType,
  34412. OnBeforeFrameUpdate: OnBeforeFrameUpdate,
  34413. OnBeforeMaterialUpdate: OnBeforeMaterialUpdate,
  34414. OnBeforeObjectUpdate: OnBeforeObjectUpdate,
  34415. OnFrameUpdate: OnFrameUpdate,
  34416. OnMaterialUpdate: OnMaterialUpdate,
  34417. OnObjectUpdate: OnObjectUpdate,
  34418. PCFShadowFilter: PCFShadowFilter,
  34419. PI: PI,
  34420. PI2: PI2,
  34421. PointShadowFilter: PointShadowFilter,
  34422. Return: Return,
  34423. Schlick_to_F0: Schlick_to_F0,
  34424. ShaderNode: ShaderNode,
  34425. Stack: Stack,
  34426. Switch: Switch,
  34427. TBNViewMatrix: TBNViewMatrix,
  34428. TWO_PI: TWO_PI,
  34429. VSMShadowFilter: VSMShadowFilter,
  34430. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  34431. Var: Var,
  34432. VarIntent: VarIntent,
  34433. abs: abs,
  34434. acesFilmicToneMapping: acesFilmicToneMapping,
  34435. acos: acos,
  34436. acosh: acosh,
  34437. add: add,
  34438. addMethodChaining: addMethodChaining,
  34439. addNodeElement: addNodeElement,
  34440. agxToneMapping: agxToneMapping,
  34441. all: all,
  34442. alphaT: alphaT,
  34443. ambientOcclusion: ambientOcclusion,
  34444. and: and,
  34445. anisotropy: anisotropy,
  34446. anisotropyB: anisotropyB,
  34447. anisotropyT: anisotropyT,
  34448. any: any,
  34449. array: array,
  34450. asin: asin,
  34451. asinh: asinh,
  34452. assign: assign,
  34453. atan: atan,
  34454. atanh: atanh,
  34455. atomicAdd: atomicAdd,
  34456. atomicAnd: atomicAnd,
  34457. atomicFunc: atomicFunc,
  34458. atomicLoad: atomicLoad,
  34459. atomicMax: atomicMax,
  34460. atomicMin: atomicMin,
  34461. atomicOr: atomicOr,
  34462. atomicStore: atomicStore,
  34463. atomicSub: atomicSub,
  34464. atomicXor: atomicXor,
  34465. attenuationColor: attenuationColor,
  34466. attenuationDistance: attenuationDistance,
  34467. attribute: attribute,
  34468. attributeArray: attributeArray,
  34469. backgroundBlurriness: backgroundBlurriness,
  34470. backgroundIntensity: backgroundIntensity,
  34471. backgroundRotation: backgroundRotation,
  34472. batch: batch,
  34473. batchColor: batchColor,
  34474. bentNormalView: bentNormalView,
  34475. billboarding: billboarding,
  34476. bitAnd: bitAnd,
  34477. bitNot: bitNot,
  34478. bitOr: bitOr,
  34479. bitXor: bitXor,
  34480. bitangentGeometry: bitangentGeometry,
  34481. bitangentLocal: bitangentLocal,
  34482. bitangentView: bitangentView,
  34483. bitangentWorld: bitangentWorld,
  34484. bitcast: bitcast,
  34485. blendBurn: blendBurn,
  34486. blendColor: blendColor,
  34487. blendDodge: blendDodge,
  34488. blendOverlay: blendOverlay,
  34489. blendScreen: blendScreen,
  34490. bool: bool,
  34491. buffer: buffer,
  34492. bufferAttribute: bufferAttribute,
  34493. builtin: builtin,
  34494. builtinAOContext: builtinAOContext,
  34495. builtinShadowContext: builtinShadowContext,
  34496. bumpMap: bumpMap,
  34497. bvec2: bvec2,
  34498. bvec3: bvec3,
  34499. bvec4: bvec4,
  34500. bypass: bypass,
  34501. cache: cache,
  34502. call: call,
  34503. cameraFar: cameraFar,
  34504. cameraIndex: cameraIndex,
  34505. cameraNear: cameraNear,
  34506. cameraNormalMatrix: cameraNormalMatrix,
  34507. cameraPosition: cameraPosition,
  34508. cameraProjectionMatrix: cameraProjectionMatrix,
  34509. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  34510. cameraViewMatrix: cameraViewMatrix,
  34511. cameraViewport: cameraViewport,
  34512. cameraWorldMatrix: cameraWorldMatrix,
  34513. cbrt: cbrt,
  34514. cdl: cdl,
  34515. ceil: ceil,
  34516. checker: checker,
  34517. cineonToneMapping: cineonToneMapping,
  34518. clamp: clamp,
  34519. clearcoat: clearcoat,
  34520. clearcoatNormalView: clearcoatNormalView,
  34521. clearcoatRoughness: clearcoatRoughness,
  34522. clipSpace: clipSpace,
  34523. code: code,
  34524. color: color,
  34525. colorSpaceToWorking: colorSpaceToWorking,
  34526. colorToDirection: colorToDirection,
  34527. compute: compute,
  34528. computeKernel: computeKernel,
  34529. computeSkinning: computeSkinning,
  34530. context: context,
  34531. convert: convert,
  34532. convertColorSpace: convertColorSpace,
  34533. convertToTexture: convertToTexture,
  34534. cos: cos,
  34535. cosh: cosh,
  34536. countLeadingZeros: countLeadingZeros,
  34537. countOneBits: countOneBits,
  34538. countTrailingZeros: countTrailingZeros,
  34539. cross: cross,
  34540. cubeTexture: cubeTexture,
  34541. cubeTextureBase: cubeTextureBase,
  34542. dFdx: dFdx,
  34543. dFdy: dFdy,
  34544. dashSize: dashSize,
  34545. debug: debug,
  34546. decrement: decrement,
  34547. decrementBefore: decrementBefore,
  34548. defaultBuildStages: defaultBuildStages,
  34549. defaultShaderStages: defaultShaderStages,
  34550. defined: defined,
  34551. degrees: degrees,
  34552. deltaTime: deltaTime,
  34553. densityFogFactor: densityFogFactor,
  34554. depth: depth,
  34555. depthPass: depthPass,
  34556. determinant: determinant,
  34557. difference: difference,
  34558. diffuseColor: diffuseColor,
  34559. diffuseContribution: diffuseContribution,
  34560. directPointLight: directPointLight,
  34561. directionToColor: directionToColor,
  34562. directionToFaceDirection: directionToFaceDirection,
  34563. dispersion: dispersion,
  34564. disposeShadowMaterial: disposeShadowMaterial,
  34565. distance: distance,
  34566. div: div,
  34567. dot: dot,
  34568. drawIndex: drawIndex,
  34569. dynamicBufferAttribute: dynamicBufferAttribute,
  34570. element: element,
  34571. emissive: emissive,
  34572. equal: equal,
  34573. equirectDirection: equirectDirection,
  34574. equirectUV: equirectUV,
  34575. exp: exp,
  34576. exp2: exp2,
  34577. exponentialHeightFogFactor: exponentialHeightFogFactor,
  34578. expression: expression,
  34579. faceDirection: faceDirection,
  34580. faceForward: faceForward,
  34581. faceforward: faceforward,
  34582. float: float,
  34583. floatBitsToInt: floatBitsToInt,
  34584. floatBitsToUint: floatBitsToUint,
  34585. floor: floor,
  34586. fog: fog,
  34587. fract: fract,
  34588. frameGroup: frameGroup,
  34589. frameId: frameId,
  34590. frontFacing: frontFacing,
  34591. fwidth: fwidth,
  34592. gain: gain,
  34593. gapSize: gapSize,
  34594. getConstNodeType: getConstNodeType,
  34595. getCurrentStack: getCurrentStack,
  34596. getDistanceAttenuation: getDistanceAttenuation,
  34597. getGeometryRoughness: getGeometryRoughness,
  34598. getNormalFromDepth: getNormalFromDepth,
  34599. getParallaxCorrectNormal: getParallaxCorrectNormal,
  34600. getRoughness: getRoughness,
  34601. getScreenPosition: getScreenPosition,
  34602. getScreenPositionFromClip: getScreenPositionFromClip,
  34603. getShIrradianceAt: getShIrradianceAt,
  34604. getShadowMaterial: getShadowMaterial,
  34605. getShadowRenderObjectFunction: getShadowRenderObjectFunction,
  34606. getTextureIndex: getTextureIndex,
  34607. getViewPosition: getViewPosition,
  34608. globalId: globalId,
  34609. glsl: glsl,
  34610. glslFn: glslFn,
  34611. grayscale: grayscale,
  34612. greaterThan: greaterThan,
  34613. greaterThanEqual: greaterThanEqual,
  34614. hash: hash,
  34615. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  34616. highpModelViewMatrix: highpModelViewMatrix,
  34617. hue: hue,
  34618. increment: increment,
  34619. incrementBefore: incrementBefore,
  34620. inspector: inspector,
  34621. instance: instance,
  34622. instanceColor: instanceColor,
  34623. instanceIndex: instanceIndex,
  34624. instancedArray: instancedArray,
  34625. instancedBufferAttribute: instancedBufferAttribute,
  34626. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  34627. instancedMesh: instancedMesh,
  34628. int: int,
  34629. intBitsToFloat: intBitsToFloat,
  34630. interleavedGradientNoise: interleavedGradientNoise,
  34631. inverse: inverse,
  34632. inverseSqrt: inverseSqrt,
  34633. inversesqrt: inversesqrt,
  34634. invocationLocalIndex: invocationLocalIndex,
  34635. invocationSubgroupIndex: invocationSubgroupIndex,
  34636. ior: ior,
  34637. iridescence: iridescence,
  34638. iridescenceIOR: iridescenceIOR,
  34639. iridescenceThickness: iridescenceThickness,
  34640. isolate: isolate,
  34641. ivec2: ivec2,
  34642. ivec3: ivec3,
  34643. ivec4: ivec4,
  34644. js: js,
  34645. label: label,
  34646. length: length,
  34647. lengthSq: lengthSq,
  34648. lessThan: lessThan,
  34649. lessThanEqual: lessThanEqual,
  34650. lightPosition: lightPosition,
  34651. lightProjectionUV: lightProjectionUV,
  34652. lightShadowMatrix: lightShadowMatrix,
  34653. lightTargetDirection: lightTargetDirection,
  34654. lightTargetPosition: lightTargetPosition,
  34655. lightViewPosition: lightViewPosition,
  34656. lightingContext: lightingContext,
  34657. lights: lights,
  34658. linearDepth: linearDepth,
  34659. linearToneMapping: linearToneMapping,
  34660. localId: localId,
  34661. log: log,
  34662. log2: log2,
  34663. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  34664. luminance: luminance,
  34665. mat2: mat2,
  34666. mat3: mat3,
  34667. mat4: mat4,
  34668. matcapUV: matcapUV,
  34669. materialAO: materialAO,
  34670. materialAlphaTest: materialAlphaTest,
  34671. materialAnisotropy: materialAnisotropy,
  34672. materialAnisotropyVector: materialAnisotropyVector,
  34673. materialAttenuationColor: materialAttenuationColor,
  34674. materialAttenuationDistance: materialAttenuationDistance,
  34675. materialClearcoat: materialClearcoat,
  34676. materialClearcoatNormal: materialClearcoatNormal,
  34677. materialClearcoatRoughness: materialClearcoatRoughness,
  34678. materialColor: materialColor,
  34679. materialDispersion: materialDispersion,
  34680. materialEmissive: materialEmissive,
  34681. materialEnvIntensity: materialEnvIntensity,
  34682. materialEnvRotation: materialEnvRotation,
  34683. materialIOR: materialIOR,
  34684. materialIridescence: materialIridescence,
  34685. materialIridescenceIOR: materialIridescenceIOR,
  34686. materialIridescenceThickness: materialIridescenceThickness,
  34687. materialLightMap: materialLightMap,
  34688. materialLineDashOffset: materialLineDashOffset,
  34689. materialLineDashSize: materialLineDashSize,
  34690. materialLineGapSize: materialLineGapSize,
  34691. materialLineScale: materialLineScale,
  34692. materialLineWidth: materialLineWidth,
  34693. materialMetalness: materialMetalness,
  34694. materialNormal: materialNormal,
  34695. materialOpacity: materialOpacity,
  34696. materialPointSize: materialPointSize,
  34697. materialReference: materialReference,
  34698. materialReflectivity: materialReflectivity,
  34699. materialRefractionRatio: materialRefractionRatio,
  34700. materialRetroreflective: materialRetroreflective,
  34701. materialRotation: materialRotation,
  34702. materialRoughness: materialRoughness,
  34703. materialSheen: materialSheen,
  34704. materialSheenRoughness: materialSheenRoughness,
  34705. materialShininess: materialShininess,
  34706. materialSpecular: materialSpecular,
  34707. materialSpecularColor: materialSpecularColor,
  34708. materialSpecularIntensity: materialSpecularIntensity,
  34709. materialSpecularStrength: materialSpecularStrength,
  34710. materialThickness: materialThickness,
  34711. materialTransmission: materialTransmission,
  34712. max: max$1,
  34713. maxMipLevel: maxMipLevel,
  34714. mediumpModelViewMatrix: mediumpModelViewMatrix,
  34715. metalness: metalness,
  34716. min: min$1,
  34717. mix: mix,
  34718. mixElement: mixElement,
  34719. mod: mod,
  34720. modelDirection: modelDirection,
  34721. modelNormalMatrix: modelNormalMatrix,
  34722. modelPosition: modelPosition,
  34723. modelRadius: modelRadius,
  34724. modelScale: modelScale,
  34725. modelViewMatrix: modelViewMatrix,
  34726. modelViewPosition: modelViewPosition,
  34727. modelViewProjection: modelViewProjection,
  34728. modelWorldMatrix: modelWorldMatrix,
  34729. modelWorldMatrixInverse: modelWorldMatrixInverse,
  34730. morphReference: morphReference,
  34731. mrt: mrt,
  34732. mul: mul,
  34733. mx_aastep: mx_aastep,
  34734. mx_add: mx_add,
  34735. mx_atan2: mx_atan2,
  34736. mx_cell_noise_float: mx_cell_noise_float,
  34737. mx_contrast: mx_contrast,
  34738. mx_divide: mx_divide,
  34739. mx_fractal_noise_float: mx_fractal_noise_float,
  34740. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  34741. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  34742. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  34743. mx_frame: mx_frame,
  34744. mx_heighttonormal: mx_heighttonormal,
  34745. mx_hsvtorgb: mx_hsvtorgb,
  34746. mx_ifequal: mx_ifequal,
  34747. mx_ifgreater: mx_ifgreater,
  34748. mx_ifgreatereq: mx_ifgreatereq,
  34749. mx_invert: mx_invert,
  34750. mx_modulo: mx_modulo,
  34751. mx_multiply: mx_multiply,
  34752. mx_noise_float: mx_noise_float,
  34753. mx_noise_vec3: mx_noise_vec3,
  34754. mx_noise_vec4: mx_noise_vec4,
  34755. mx_place2d: mx_place2d,
  34756. mx_power: mx_power,
  34757. mx_ramp4: mx_ramp4,
  34758. mx_ramplr: mx_ramplr,
  34759. mx_ramptb: mx_ramptb,
  34760. mx_rgbtohsv: mx_rgbtohsv,
  34761. mx_rotate2d: mx_rotate2d,
  34762. mx_rotate3d: mx_rotate3d,
  34763. mx_safepower: mx_safepower,
  34764. mx_separate: mx_separate,
  34765. mx_splitlr: mx_splitlr,
  34766. mx_splittb: mx_splittb,
  34767. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  34768. mx_subtract: mx_subtract,
  34769. mx_timer: mx_timer,
  34770. mx_transform_uv: mx_transform_uv,
  34771. mx_unifiednoise2d: mx_unifiednoise2d,
  34772. mx_unifiednoise3d: mx_unifiednoise3d,
  34773. mx_worley_noise_float: mx_worley_noise_float,
  34774. mx_worley_noise_vec2: mx_worley_noise_vec2,
  34775. mx_worley_noise_vec3: mx_worley_noise_vec3,
  34776. negate: negate,
  34777. negateOnBackSide: negateOnBackSide,
  34778. neutralToneMapping: neutralToneMapping,
  34779. nodeArray: nodeArray,
  34780. nodeImmutable: nodeImmutable,
  34781. nodeObject: nodeObject,
  34782. nodeObjectIntent: nodeObjectIntent,
  34783. nodeObjects: nodeObjects,
  34784. nodeProxy: nodeProxy,
  34785. nodeProxyConstructor: nodeProxyConstructor,
  34786. nodeProxyIntent: nodeProxyIntent,
  34787. normalFlat: normalFlat,
  34788. normalGeometry: normalGeometry,
  34789. normalLocal: normalLocal,
  34790. normalMap: normalMap,
  34791. normalView: normalView,
  34792. normalViewGeometry: normalViewGeometry,
  34793. normalWorld: normalWorld,
  34794. normalWorldGeometry: normalWorldGeometry,
  34795. normalize: normalize,
  34796. not: not,
  34797. notEqual: notEqual,
  34798. numWorkgroups: numWorkgroups,
  34799. objectDirection: objectDirection,
  34800. objectGroup: objectGroup,
  34801. objectPosition: objectPosition,
  34802. objectRadius: objectRadius,
  34803. objectScale: objectScale,
  34804. objectViewPosition: objectViewPosition,
  34805. objectWorldMatrix: objectWorldMatrix,
  34806. oneMinus: oneMinus,
  34807. or: or,
  34808. orthographicDepthToViewZ: orthographicDepthToViewZ,
  34809. oscSawtooth: oscSawtooth,
  34810. oscSine: oscSine,
  34811. oscSquare: oscSquare,
  34812. oscTriangle: oscTriangle,
  34813. output: output,
  34814. outputStruct: outputStruct,
  34815. overloadingFn: overloadingFn,
  34816. overrideNode: overrideNode,
  34817. overrideNodes: overrideNodes,
  34818. packHalf2x16: packHalf2x16,
  34819. packNormalToRGB: packNormalToRGB,
  34820. packSnorm2x16: packSnorm2x16,
  34821. packUnorm2x16: packUnorm2x16,
  34822. parabola: parabola,
  34823. parallaxDirection: parallaxDirection,
  34824. parallaxUV: parallaxUV,
  34825. parameter: parameter,
  34826. pass: pass,
  34827. passTexture: passTexture,
  34828. pcurve: pcurve,
  34829. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  34830. pmremTexture: pmremTexture,
  34831. pointShadow: pointShadow,
  34832. pointUV: pointUV,
  34833. pointWidth: pointWidth,
  34834. positionGeometry: positionGeometry,
  34835. positionLocal: positionLocal,
  34836. positionPrevious: positionPrevious,
  34837. positionView: positionView,
  34838. positionViewDirection: positionViewDirection,
  34839. positionWorld: positionWorld,
  34840. positionWorldDirection: positionWorldDirection,
  34841. posterize: posterize,
  34842. pow: pow,
  34843. pow2: pow2,
  34844. pow3: pow3,
  34845. pow4: pow4,
  34846. premultiplyAlpha: premultiplyAlpha,
  34847. property: property,
  34848. quadBroadcast: quadBroadcast,
  34849. quadSwapDiagonal: quadSwapDiagonal,
  34850. quadSwapX: quadSwapX,
  34851. quadSwapY: quadSwapY,
  34852. radians: radians,
  34853. rand: rand,
  34854. range: range,
  34855. rangeFogFactor: rangeFogFactor,
  34856. reciprocal: reciprocal,
  34857. reference: reference,
  34858. referenceBuffer: referenceBuffer,
  34859. reflect: reflect,
  34860. reflectVector: reflectVector,
  34861. reflectView: reflectView,
  34862. reflector: reflector,
  34863. refract: refract,
  34864. refractVector: refractVector,
  34865. refractView: refractView,
  34866. reinhardToneMapping: reinhardToneMapping,
  34867. remap: remap,
  34868. remapClamp: remapClamp,
  34869. renderGroup: renderGroup,
  34870. renderOutput: renderOutput,
  34871. rendererReference: rendererReference,
  34872. replaceDefaultUV: replaceDefaultUV,
  34873. retroreflective: retroreflective,
  34874. rotate: rotate,
  34875. rotateUV: rotateUV,
  34876. roughness: roughness,
  34877. round: round,
  34878. rtt: rtt,
  34879. sRGBTransferEOTF: sRGBTransferEOTF,
  34880. sRGBTransferOETF: sRGBTransferOETF,
  34881. sample: sample,
  34882. sampler: sampler,
  34883. samplerComparison: samplerComparison,
  34884. saturate: saturate,
  34885. saturation: saturation,
  34886. screenCoordinate: screenCoordinate,
  34887. screenDPR: screenDPR,
  34888. screenSize: screenSize,
  34889. screenUV: screenUV,
  34890. select: select,
  34891. setCurrentStack: setCurrentStack,
  34892. setName: setName,
  34893. shaderStages: shaderStages,
  34894. shadow: shadow,
  34895. shadowPositionWorld: shadowPositionWorld,
  34896. shapeCircle: shapeCircle,
  34897. sharedUniformGroup: sharedUniformGroup,
  34898. sheen: sheen,
  34899. sheenRoughness: sheenRoughness,
  34900. shiftLeft: shiftLeft,
  34901. shiftRight: shiftRight,
  34902. shininess: shininess,
  34903. sign: sign,
  34904. sin: sin,
  34905. sinc: sinc,
  34906. sinh: sinh,
  34907. skinning: skinning,
  34908. smoothstep: smoothstep,
  34909. smoothstepElement: smoothstepElement,
  34910. specularColor: specularColor,
  34911. specularColorBlended: specularColorBlended,
  34912. specularF90: specularF90,
  34913. spherizeUV: spherizeUV,
  34914. split: split,
  34915. spritesheetUV: spritesheetUV,
  34916. sqrt: sqrt,
  34917. stack: stack,
  34918. step: step,
  34919. stepElement: stepElement,
  34920. storage: storage,
  34921. storageBarrier: storageBarrier,
  34922. storageTexture: storageTexture,
  34923. storageTexture3D: storageTexture3D,
  34924. struct: struct,
  34925. sub: sub,
  34926. subBuild: subBuild,
  34927. subgroupAdd: subgroupAdd,
  34928. subgroupAll: subgroupAll,
  34929. subgroupAnd: subgroupAnd,
  34930. subgroupAny: subgroupAny,
  34931. subgroupBallot: subgroupBallot,
  34932. subgroupBroadcast: subgroupBroadcast,
  34933. subgroupBroadcastFirst: subgroupBroadcastFirst,
  34934. subgroupElect: subgroupElect,
  34935. subgroupExclusiveAdd: subgroupExclusiveAdd,
  34936. subgroupExclusiveMul: subgroupExclusiveMul,
  34937. subgroupInclusiveAdd: subgroupInclusiveAdd,
  34938. subgroupInclusiveMul: subgroupInclusiveMul,
  34939. subgroupIndex: subgroupIndex,
  34940. subgroupMax: subgroupMax,
  34941. subgroupMin: subgroupMin,
  34942. subgroupMul: subgroupMul,
  34943. subgroupOr: subgroupOr,
  34944. subgroupShuffle: subgroupShuffle,
  34945. subgroupShuffleDown: subgroupShuffleDown,
  34946. subgroupShuffleUp: subgroupShuffleUp,
  34947. subgroupShuffleXor: subgroupShuffleXor,
  34948. subgroupSize: subgroupSize,
  34949. subgroupXor: subgroupXor,
  34950. tan: tan,
  34951. tangentGeometry: tangentGeometry,
  34952. tangentLocal: tangentLocal,
  34953. tangentView: tangentView,
  34954. tangentWorld: tangentWorld,
  34955. tanh: tanh,
  34956. texture: texture,
  34957. texture3D: texture3D,
  34958. texture3DLevel: texture3DLevel,
  34959. texture3DLoad: texture3DLoad,
  34960. textureBarrier: textureBarrier,
  34961. textureBicubic: textureBicubic,
  34962. textureBicubicLevel: textureBicubicLevel,
  34963. textureLevel: textureLevel,
  34964. textureLoad: textureLoad,
  34965. textureSize: textureSize,
  34966. textureStore: textureStore,
  34967. thickness: thickness,
  34968. time: time,
  34969. toneMapping: toneMapping,
  34970. toneMappingExposure: toneMappingExposure,
  34971. toonOutlinePass: toonOutlinePass,
  34972. transformDirection: transformDirection,
  34973. transformNormal: transformNormal,
  34974. transformNormalByInverseViewMatrix: transformNormalByInverseViewMatrix,
  34975. transformNormalByViewMatrix: transformNormalByViewMatrix,
  34976. transformNormalToView: transformNormalToView,
  34977. transformedClearcoatNormalView: transformedClearcoatNormalView,
  34978. transformedNormalView: transformedNormalView,
  34979. transformedNormalWorld: transformedNormalWorld,
  34980. transmission: transmission,
  34981. transpose: transpose,
  34982. triNoise3D: triNoise3D,
  34983. triplanarTexture: triplanarTexture,
  34984. triplanarTextures: triplanarTextures,
  34985. trunc: trunc,
  34986. uint: uint,
  34987. uintBitsToFloat: uintBitsToFloat,
  34988. uniform: uniform,
  34989. uniformArray: uniformArray,
  34990. uniformCubeTexture: uniformCubeTexture,
  34991. uniformFlow: uniformFlow,
  34992. uniformGroup: uniformGroup,
  34993. uniformTexture: uniformTexture,
  34994. unpackHalf2x16: unpackHalf2x16,
  34995. unpackNormal: unpackNormal,
  34996. unpackRGBToNormal: unpackRGBToNormal,
  34997. unpackSnorm2x16: unpackSnorm2x16,
  34998. unpackUnorm2x16: unpackUnorm2x16,
  34999. unpremultiplyAlpha: unpremultiplyAlpha,
  35000. userData: userData,
  35001. uv: uv$1,
  35002. uvec2: uvec2,
  35003. uvec3: uvec3,
  35004. uvec4: uvec4,
  35005. varying: varying,
  35006. varyingProperty: varyingProperty,
  35007. vec2: vec2,
  35008. vec3: vec3,
  35009. vec4: vec4,
  35010. vectorComponents: vectorComponents,
  35011. velocity: velocity,
  35012. vertexColor: vertexColor,
  35013. vertexIndex: vertexIndex,
  35014. vertexStage: vertexStage,
  35015. vibrance: vibrance,
  35016. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  35017. viewZToOrthographicDepth: viewZToOrthographicDepth,
  35018. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  35019. viewZToReversedOrthographicDepth: viewZToReversedOrthographicDepth,
  35020. viewZToReversedPerspectiveDepth: viewZToReversedPerspectiveDepth,
  35021. viewport: viewport,
  35022. viewportCoordinate: viewportCoordinate,
  35023. viewportDepthTexture: viewportDepthTexture,
  35024. viewportLinearDepth: viewportLinearDepth,
  35025. viewportMipTexture: viewportMipTexture,
  35026. viewportOpaqueMipTexture: viewportOpaqueMipTexture,
  35027. viewportSafeUV: viewportSafeUV,
  35028. viewportSharedTexture: viewportSharedTexture,
  35029. viewportSize: viewportSize,
  35030. viewportTexture: viewportTexture,
  35031. viewportUV: viewportUV,
  35032. vogelDiskSample: vogelDiskSample,
  35033. wgsl: wgsl,
  35034. wgslFn: wgslFn,
  35035. workgroupArray: workgroupArray,
  35036. workgroupBarrier: workgroupBarrier,
  35037. workgroupId: workgroupId,
  35038. workingToColorSpace: workingToColorSpace,
  35039. xor: xor
  35040. });
  35041. const _clearColor = /*@__PURE__*/ new Color4();
  35042. /**
  35043. * This renderer module manages the background.
  35044. *
  35045. * @private
  35046. * @augments DataMap
  35047. */
  35048. class Background extends DataMap {
  35049. /**
  35050. * Constructs a new background management component.
  35051. *
  35052. * @param {Renderer} renderer - The renderer.
  35053. * @param {NodeManager} nodes - Renderer component for managing nodes related logic.
  35054. */
  35055. constructor( renderer, nodes ) {
  35056. super();
  35057. /**
  35058. * The renderer.
  35059. *
  35060. * @type {Renderer}
  35061. */
  35062. this.renderer = renderer;
  35063. /**
  35064. * Renderer component for managing nodes related logic.
  35065. *
  35066. * @type {NodeManager}
  35067. */
  35068. this.nodes = nodes;
  35069. }
  35070. /**
  35071. * Updates the background for the given scene. Depending on how `Scene.background`
  35072. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  35073. * or add a mesh to the render list for rendering the background as a textured plane
  35074. * or skybox.
  35075. *
  35076. * @param {Scene} scene - The scene.
  35077. * @param {RenderList} renderList - The current render list.
  35078. * @param {RenderContext} renderContext - The current render context.
  35079. */
  35080. update( scene, renderList, renderContext ) {
  35081. const renderer = this.renderer;
  35082. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  35083. let forceClear = false;
  35084. if ( background === null ) {
  35085. // no background settings, use clear color configuration from the renderer
  35086. renderer._clearColor.getRGB( _clearColor );
  35087. _clearColor.a = renderer._clearColor.a;
  35088. } else if ( background.isColor === true ) {
  35089. // background is an opaque color
  35090. background.getRGB( _clearColor );
  35091. _clearColor.a = 1;
  35092. forceClear = true;
  35093. } else if ( background.isNode === true ) {
  35094. const sceneData = this.get( scene );
  35095. const backgroundNode = background;
  35096. _clearColor.copy( renderer._clearColor );
  35097. let backgroundMesh = sceneData.backgroundMesh;
  35098. if ( backgroundMesh === undefined ) {
  35099. const backgroundMeshNode = vec4( backgroundNode ).mul( backgroundIntensity ).context( {
  35100. // @TODO: Add Texture2D support using node context
  35101. getUV: () => backgroundRotation.mul( normalWorldGeometry ),
  35102. getTextureLevel: () => backgroundBlurriness
  35103. } );
  35104. // when using orthographic cameras, we must scale the skybox sphere
  35105. // up to exceed the dimensions of the camera's viewing box.
  35106. const isOrtho = cameraProjectionMatrix.element( 3 ).element( 3 ).equal( 1.0 );
  35107. // calculate the orthographic scale
  35108. // projectionMatrix[1][1] is (1 / top). Invert it to get the height and multiply by 3.0
  35109. // (an arbitrary safety factor) to ensure the skybox is large enough to cover the corners
  35110. // of the rectangular screen
  35111. const orthoScale = div( 1.0, cameraProjectionMatrix.element( 1 ).element( 1 ) ).mul( 3.0 );
  35112. // compute vertex position
  35113. const modifiedPosition = isOrtho.select( positionLocal.mul( orthoScale ), positionLocal );
  35114. // by using a w component of 0, the skybox will not translate when the camera moves through the scene
  35115. const viewPosition = modelViewMatrix.mul( vec4( modifiedPosition, 0.0 ) );
  35116. // we force w=1.0 here to prevent the w_clip=0 divide-by-zero error for ortho cameras.
  35117. let viewProj = cameraProjectionMatrix.mul( vec4( viewPosition.xyz, 1.0 ) );
  35118. // force background to far plane so it does not occlude objects
  35119. viewProj = viewProj.setZ( viewProj.w );
  35120. const nodeMaterial = new NodeMaterial();
  35121. nodeMaterial.name = 'Background.material';
  35122. nodeMaterial.side = BackSide;
  35123. nodeMaterial.depthTest = false;
  35124. nodeMaterial.depthWrite = false;
  35125. nodeMaterial.allowOverride = false;
  35126. nodeMaterial.fog = false;
  35127. nodeMaterial.lights = false;
  35128. nodeMaterial.vertexNode = viewProj;
  35129. nodeMaterial.colorNode = backgroundMeshNode;
  35130. sceneData.backgroundMeshNode = backgroundMeshNode;
  35131. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  35132. backgroundMesh.frustumCulled = false;
  35133. backgroundMesh.name = 'Background.mesh';
  35134. function onBackgroundDispose() {
  35135. background.removeEventListener( 'dispose', onBackgroundDispose );
  35136. backgroundMesh.material.dispose();
  35137. backgroundMesh.geometry.dispose();
  35138. }
  35139. background.addEventListener( 'dispose', onBackgroundDispose );
  35140. }
  35141. const backgroundCacheKey = backgroundNode.getCacheKey();
  35142. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  35143. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  35144. sceneData.backgroundMeshNode.needsUpdate = true;
  35145. backgroundMesh.material.needsUpdate = true;
  35146. sceneData.backgroundCacheKey = backgroundCacheKey;
  35147. }
  35148. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  35149. } else {
  35150. error( 'Renderer: Unsupported background configuration.', background );
  35151. }
  35152. //
  35153. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  35154. if ( environmentBlendMode === 'additive' ) {
  35155. _clearColor.set( 0, 0, 0, 1 );
  35156. } else if ( environmentBlendMode === 'alpha-blend' ) {
  35157. _clearColor.set( 0, 0, 0, 0 );
  35158. }
  35159. //
  35160. if ( renderer.autoClear === true || forceClear === true ) {
  35161. const clearColorValue = renderContext.clearColorValue;
  35162. clearColorValue.r = _clearColor.r;
  35163. clearColorValue.g = _clearColor.g;
  35164. clearColorValue.b = _clearColor.b;
  35165. clearColorValue.a = _clearColor.a;
  35166. // premultiply alpha
  35167. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  35168. clearColorValue.r *= clearColorValue.a;
  35169. clearColorValue.g *= clearColorValue.a;
  35170. clearColorValue.b *= clearColorValue.a;
  35171. }
  35172. //
  35173. renderContext.depthClearValue = renderer.getClearDepth();
  35174. renderContext.stencilClearValue = renderer.getClearStencil();
  35175. renderContext.clearColor = renderer.autoClearColor === true;
  35176. renderContext.clearDepth = renderer.autoClearDepth === true;
  35177. renderContext.clearStencil = renderer.autoClearStencil === true;
  35178. } else {
  35179. renderContext.clearColor = false;
  35180. renderContext.clearDepth = false;
  35181. renderContext.clearStencil = false;
  35182. }
  35183. }
  35184. }
  35185. let _id$7 = 0;
  35186. /**
  35187. * A bind group represents a collection of bindings and thus a collection
  35188. * or resources. Bind groups are assigned to pipelines to provide them
  35189. * with the required resources (like uniform buffers or textures).
  35190. *
  35191. * @private
  35192. */
  35193. class BindGroup {
  35194. /**
  35195. * Constructs a new bind group.
  35196. *
  35197. * @param {string} name - The bind group's name.
  35198. * @param {Array<Binding>} bindings - An array of bindings.
  35199. * @param {number} index - The group index.
  35200. */
  35201. constructor( name = '', bindings = [] ) {
  35202. /**
  35203. * The bind group's name.
  35204. *
  35205. * @type {string}
  35206. */
  35207. this.name = name;
  35208. /**
  35209. * An array of bindings.
  35210. *
  35211. * @type {Array<Binding>}
  35212. */
  35213. this.bindings = bindings;
  35214. /**
  35215. * The group's ID.
  35216. *
  35217. * @type {number}
  35218. */
  35219. this.id = _id$7 ++;
  35220. }
  35221. }
  35222. /**
  35223. * This module represents the state of a node builder after it was
  35224. * used to build the nodes for a render object. The state holds the
  35225. * results of the build for further processing in the renderer.
  35226. *
  35227. * Render objects with identical cache keys share the same node builder state.
  35228. *
  35229. * @private
  35230. */
  35231. class NodeBuilderState {
  35232. /**
  35233. * Constructs a new node builder state.
  35234. *
  35235. * @param {string} vertexShader - The native vertex shader code.
  35236. * @param {string} fragmentShader - The native fragment shader code.
  35237. * @param {string} computeShader - The native compute shader code.
  35238. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  35239. * @param {Array<BindGroup>} bindings - An array of bind groups.
  35240. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  35241. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  35242. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  35243. * @param {NodeMaterialObserver} observer - A node material observer.
  35244. * @param {boolean} hardwareClipping - Whether the built material uses hardware clipping or not.
  35245. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  35246. */
  35247. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, hardwareClipping, transforms = [] ) {
  35248. /**
  35249. * The native vertex shader code.
  35250. *
  35251. * @type {string}
  35252. */
  35253. this.vertexShader = vertexShader;
  35254. /**
  35255. * The native fragment shader code.
  35256. *
  35257. * @type {string}
  35258. */
  35259. this.fragmentShader = fragmentShader;
  35260. /**
  35261. * The native compute shader code.
  35262. *
  35263. * @type {string}
  35264. */
  35265. this.computeShader = computeShader;
  35266. /**
  35267. * An array with transform attribute objects.
  35268. * Only relevant when using compute shaders with WebGL 2.
  35269. *
  35270. * @type {Array<Object>}
  35271. */
  35272. this.transforms = transforms;
  35273. /**
  35274. * An array of node attributes representing
  35275. * the attributes of the shaders.
  35276. *
  35277. * @type {Array<NodeAttribute>}
  35278. */
  35279. this.nodeAttributes = nodeAttributes;
  35280. /**
  35281. * An array of bind groups representing the uniform or storage
  35282. * buffers, texture or samplers of the shader.
  35283. *
  35284. * @type {Array<BindGroup>}
  35285. */
  35286. this.bindings = bindings;
  35287. /**
  35288. * An array of nodes that implement their `update()` method.
  35289. *
  35290. * @type {Array<Node>}
  35291. */
  35292. this.updateNodes = updateNodes;
  35293. /**
  35294. * An array of nodes that implement their `updateBefore()` method.
  35295. *
  35296. * @type {Array<Node>}
  35297. */
  35298. this.updateBeforeNodes = updateBeforeNodes;
  35299. /**
  35300. * An array of nodes that implement their `updateAfter()` method.
  35301. *
  35302. * @type {Array<Node>}
  35303. */
  35304. this.updateAfterNodes = updateAfterNodes;
  35305. /**
  35306. * A node material observer.
  35307. *
  35308. * @type {NodeMaterialObserver}
  35309. */
  35310. this.observer = observer;
  35311. /**
  35312. * Whether the built material uses hardware clipping or not.
  35313. *
  35314. * @type {boolean}
  35315. */
  35316. this.hardwareClipping = hardwareClipping;
  35317. /**
  35318. * How often this state is used by render objects.
  35319. *
  35320. * @type {number}
  35321. */
  35322. this.usedTimes = 0;
  35323. }
  35324. /**
  35325. * This method is used to create a array of bind groups based
  35326. * on the existing bind groups of this state. Shared groups are
  35327. * not cloned.
  35328. *
  35329. * @return {Array<BindGroup>} A array of bind groups.
  35330. */
  35331. createBindings() {
  35332. const bindings = [];
  35333. for ( const instanceGroup of this.bindings ) {
  35334. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  35335. if ( shared !== true ) {
  35336. const bindingsGroup = new BindGroup( instanceGroup.name, [] );
  35337. bindings.push( bindingsGroup );
  35338. for ( const instanceBinding of instanceGroup.bindings ) {
  35339. bindingsGroup.bindings.push( instanceBinding.clone() );
  35340. }
  35341. } else {
  35342. bindings.push( instanceGroup );
  35343. }
  35344. }
  35345. return bindings;
  35346. }
  35347. }
  35348. /**
  35349. * {@link NodeBuilder} is going to create instances of this class during the build process
  35350. * of nodes. They represent the final shader attributes that are going to be generated
  35351. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  35352. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  35353. */
  35354. class NodeAttribute {
  35355. /**
  35356. * Constructs a new node attribute.
  35357. *
  35358. * @param {string} name - The name of the attribute.
  35359. * @param {string} type - The type of the attribute.
  35360. * @param {?Node} node - An optional reference to the node.
  35361. */
  35362. constructor( name, type, node = null ) {
  35363. /**
  35364. * This flag can be used for type testing.
  35365. *
  35366. * @type {boolean}
  35367. * @readonly
  35368. * @default true
  35369. */
  35370. this.isNodeAttribute = true;
  35371. /**
  35372. * The name of the attribute.
  35373. *
  35374. * @type {string}
  35375. */
  35376. this.name = name;
  35377. /**
  35378. * The type of the attribute.
  35379. *
  35380. * @type {string}
  35381. */
  35382. this.type = type;
  35383. /**
  35384. * An optional reference to the node.
  35385. *
  35386. * @type {?Node}
  35387. * @default null
  35388. */
  35389. this.node = node;
  35390. }
  35391. }
  35392. /**
  35393. * {@link NodeBuilder} is going to create instances of this class during the build process
  35394. * of nodes. They represent the final shader uniforms that are going to be generated
  35395. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  35396. * for this purpose.
  35397. */
  35398. class NodeUniform {
  35399. /**
  35400. * Constructs a new node uniform.
  35401. *
  35402. * @param {string} name - The name of the uniform.
  35403. * @param {string} type - The type of the uniform.
  35404. * @param {UniformNode} node - An reference to the node.
  35405. */
  35406. constructor( name, type, node ) {
  35407. /**
  35408. * This flag can be used for type testing.
  35409. *
  35410. * @type {boolean}
  35411. * @readonly
  35412. * @default true
  35413. */
  35414. this.isNodeUniform = true;
  35415. /**
  35416. * The name of the uniform.
  35417. *
  35418. * @type {string}
  35419. */
  35420. this.name = name;
  35421. /**
  35422. * The type of the uniform.
  35423. *
  35424. * @type {string}
  35425. */
  35426. this.type = type;
  35427. /**
  35428. * An reference to the node.
  35429. *
  35430. * @type {UniformNode}
  35431. */
  35432. this.node = node;
  35433. }
  35434. /**
  35435. * The value of the uniform node.
  35436. *
  35437. * @type {any}
  35438. */
  35439. get value() {
  35440. return this.node.value;
  35441. }
  35442. set value( val ) {
  35443. this.node.value = val;
  35444. }
  35445. /**
  35446. * The id of the uniform node.
  35447. *
  35448. * @type {number}
  35449. */
  35450. get id() {
  35451. return this.node.id;
  35452. }
  35453. /**
  35454. * The uniform node's group.
  35455. *
  35456. * @type {UniformGroupNode}
  35457. */
  35458. get groupNode() {
  35459. return this.node.groupNode;
  35460. }
  35461. }
  35462. /**
  35463. * {@link NodeBuilder} is going to create instances of this class during the build process
  35464. * of nodes. They represent the final shader variables that are going to be generated
  35465. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  35466. * this purpose.
  35467. */
  35468. class NodeVar {
  35469. /**
  35470. * Constructs a new node variable.
  35471. *
  35472. * @param {string} name - The name of the variable.
  35473. * @param {string} type - The type of the variable.
  35474. * @param {boolean} [readOnly=false] - The read-only flag.
  35475. * @param {?number} [count=null] - The size.
  35476. */
  35477. constructor( name, type, readOnly = false, count = null ) {
  35478. /**
  35479. * This flag can be used for type testing.
  35480. *
  35481. * @type {boolean}
  35482. * @readonly
  35483. * @default true
  35484. */
  35485. this.isNodeVar = true;
  35486. /**
  35487. * The name of the variable.
  35488. *
  35489. * @type {string}
  35490. */
  35491. this.name = name;
  35492. /**
  35493. * The type of the variable.
  35494. *
  35495. * @type {string}
  35496. */
  35497. this.type = type;
  35498. /**
  35499. * The read-only flag.
  35500. *
  35501. * @type {boolean}
  35502. */
  35503. this.readOnly = readOnly;
  35504. /**
  35505. * The size.
  35506. *
  35507. * @type {?number}
  35508. */
  35509. this.count = count;
  35510. }
  35511. }
  35512. /**
  35513. * {@link NodeBuilder} is going to create instances of this class during the build process
  35514. * of nodes. They represent the final shader varyings that are going to be generated
  35515. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  35516. * this purpose.
  35517. *
  35518. * @augments NodeVar
  35519. */
  35520. class NodeVarying extends NodeVar {
  35521. /**
  35522. * Constructs a new node varying.
  35523. *
  35524. * @param {string} name - The name of the varying.
  35525. * @param {string} type - The type of the varying.
  35526. * @param {?string} interpolationType - The interpolation type of the varying.
  35527. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  35528. */
  35529. constructor( name, type, interpolationType = null, interpolationSampling = null ) {
  35530. super( name, type );
  35531. /**
  35532. * Whether this varying requires interpolation or not. This property can be used
  35533. * to check if the varying can be optimized for a variable.
  35534. *
  35535. * @type {boolean}
  35536. * @default false
  35537. */
  35538. this.needsInterpolation = false;
  35539. /**
  35540. * This flag can be used for type testing.
  35541. *
  35542. * @type {boolean}
  35543. * @readonly
  35544. * @default true
  35545. */
  35546. this.isNodeVarying = true;
  35547. /**
  35548. * The interpolation type of the varying data.
  35549. *
  35550. * @type {?string}
  35551. * @default null
  35552. */
  35553. this.interpolationType = interpolationType;
  35554. /**
  35555. * The interpolation sampling type of varying data.
  35556. *
  35557. * @type {?string}
  35558. * @default null
  35559. */
  35560. this.interpolationSampling = interpolationSampling;
  35561. }
  35562. }
  35563. /**
  35564. * {@link NodeBuilder} is going to create instances of this class during the build process
  35565. * of nodes. They represent user-defined, native shader code portions that are going to be
  35566. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  35567. * for this purpose.
  35568. */
  35569. class NodeCode {
  35570. /**
  35571. * Constructs a new code node.
  35572. *
  35573. * @param {string} name - The name of the code.
  35574. * @param {string} type - The node type.
  35575. * @param {string} [code=''] - The native shader code.
  35576. */
  35577. constructor( name, type, code = '' ) {
  35578. /**
  35579. * The name of the code.
  35580. *
  35581. * @type {string}
  35582. */
  35583. this.name = name;
  35584. /**
  35585. * The node type.
  35586. *
  35587. * @type {string}
  35588. */
  35589. this.type = type;
  35590. /**
  35591. * The native shader code.
  35592. *
  35593. * @type {string}
  35594. * @default ''
  35595. */
  35596. this.code = code;
  35597. Object.defineProperty( this, 'isNodeCode', { value: true } );
  35598. }
  35599. }
  35600. let _id$6 = 0;
  35601. /**
  35602. * This utility class is used in {@link NodeBuilder} as an internal
  35603. * cache data structure for node data.
  35604. */
  35605. class NodeCache {
  35606. /**
  35607. * Constructs a new node cache.
  35608. *
  35609. * @param {?NodeCache} parent - A reference to a parent cache.
  35610. */
  35611. constructor( parent = null ) {
  35612. /**
  35613. * The id of the cache.
  35614. *
  35615. * @type {number}
  35616. * @readonly
  35617. */
  35618. this.id = _id$6 ++;
  35619. /**
  35620. * A weak map for managing node data.
  35621. *
  35622. * @type {WeakMap<Node, Object>}
  35623. */
  35624. this.nodesData = new WeakMap();
  35625. /**
  35626. * Reference to a parent node cache.
  35627. *
  35628. * @type {?NodeCache}
  35629. * @default null
  35630. */
  35631. this.parent = parent;
  35632. }
  35633. /**
  35634. * Returns the data for the given node.
  35635. *
  35636. * @param {Node} node - The node.
  35637. * @return {?Object} The data for the node.
  35638. */
  35639. getData( node ) {
  35640. let data = this.nodesData.get( node );
  35641. if ( data === undefined && this.parent !== null ) {
  35642. data = this.parent.getData( node );
  35643. }
  35644. return data;
  35645. }
  35646. /**
  35647. * Sets the data for a given node.
  35648. *
  35649. * @param {Node} node - The node.
  35650. * @param {Object} data - The data that should be cached.
  35651. */
  35652. setData( node, data ) {
  35653. this.nodesData.set( node, data );
  35654. }
  35655. }
  35656. class StructType {
  35657. constructor( name, members ) {
  35658. this.name = name;
  35659. this.members = members;
  35660. this.output = false;
  35661. }
  35662. }
  35663. /**
  35664. * Abstract base class for uniforms.
  35665. *
  35666. * @abstract
  35667. * @private
  35668. */
  35669. class Uniform {
  35670. /**
  35671. * Constructs a new uniform.
  35672. *
  35673. * @param {string} name - The uniform's name.
  35674. * @param {any} value - The uniform's value.
  35675. */
  35676. constructor( name, value ) {
  35677. /**
  35678. * The uniform's name.
  35679. *
  35680. * @type {string}
  35681. */
  35682. this.name = name;
  35683. /**
  35684. * The uniform's value.
  35685. *
  35686. * @type {any}
  35687. */
  35688. this.value = value;
  35689. /**
  35690. * Used to build the uniform buffer according to the STD140 layout.
  35691. * Derived uniforms will set this property to a data type specific
  35692. * value.
  35693. *
  35694. * @type {number}
  35695. */
  35696. this.boundary = 0;
  35697. /**
  35698. * The item size. Derived uniforms will set this property to a data
  35699. * type specific value.
  35700. *
  35701. * @type {number}
  35702. */
  35703. this.itemSize = 0;
  35704. /**
  35705. * This property is set by {@link UniformsGroup} and marks
  35706. * the start position in the uniform buffer.
  35707. *
  35708. * @type {number}
  35709. */
  35710. this.offset = 0;
  35711. /**
  35712. * This property is set by {@link UniformsGroup} and marks
  35713. * the index position in the uniform array.
  35714. *
  35715. * @type {number}
  35716. */
  35717. this.index = -1;
  35718. }
  35719. /**
  35720. * Sets the uniform's value.
  35721. *
  35722. * @param {any} value - The value to set.
  35723. */
  35724. setValue( value ) {
  35725. this.value = value;
  35726. }
  35727. /**
  35728. * Returns the uniform's value.
  35729. *
  35730. * @return {any} The value.
  35731. */
  35732. getValue() {
  35733. return this.value;
  35734. }
  35735. }
  35736. /**
  35737. * Represents a Number uniform.
  35738. *
  35739. * @private
  35740. * @augments Uniform
  35741. */
  35742. class NumberUniform extends Uniform {
  35743. /**
  35744. * Constructs a new Number uniform.
  35745. *
  35746. * @param {string} name - The uniform's name.
  35747. * @param {number} value - The uniform's value.
  35748. */
  35749. constructor( name, value = 0 ) {
  35750. super( name, value );
  35751. /**
  35752. * This flag can be used for type testing.
  35753. *
  35754. * @type {boolean}
  35755. * @readonly
  35756. * @default true
  35757. */
  35758. this.isNumberUniform = true;
  35759. this.boundary = 4;
  35760. this.itemSize = 1;
  35761. }
  35762. }
  35763. /**
  35764. * Represents a Vector2 uniform.
  35765. *
  35766. * @private
  35767. * @augments Uniform
  35768. */
  35769. class Vector2Uniform extends Uniform {
  35770. /**
  35771. * Constructs a new Number uniform.
  35772. *
  35773. * @param {string} name - The uniform's name.
  35774. * @param {Vector2} value - The uniform's value.
  35775. */
  35776. constructor( name, value = new Vector2() ) {
  35777. super( name, value );
  35778. /**
  35779. * This flag can be used for type testing.
  35780. *
  35781. * @type {boolean}
  35782. * @readonly
  35783. * @default true
  35784. */
  35785. this.isVector2Uniform = true;
  35786. this.boundary = 8;
  35787. this.itemSize = 2;
  35788. }
  35789. }
  35790. /**
  35791. * Represents a Vector3 uniform.
  35792. *
  35793. * @private
  35794. * @augments Uniform
  35795. */
  35796. class Vector3Uniform extends Uniform {
  35797. /**
  35798. * Constructs a new Number uniform.
  35799. *
  35800. * @param {string} name - The uniform's name.
  35801. * @param {Vector3} value - The uniform's value.
  35802. */
  35803. constructor( name, value = new Vector3() ) {
  35804. super( name, value );
  35805. /**
  35806. * This flag can be used for type testing.
  35807. *
  35808. * @type {boolean}
  35809. * @readonly
  35810. * @default true
  35811. */
  35812. this.isVector3Uniform = true;
  35813. this.boundary = 16;
  35814. this.itemSize = 3;
  35815. }
  35816. }
  35817. /**
  35818. * Represents a Vector4 uniform.
  35819. *
  35820. * @private
  35821. * @augments Uniform
  35822. */
  35823. class Vector4Uniform extends Uniform {
  35824. /**
  35825. * Constructs a new Number uniform.
  35826. *
  35827. * @param {string} name - The uniform's name.
  35828. * @param {Vector4} value - The uniform's value.
  35829. */
  35830. constructor( name, value = new Vector4() ) {
  35831. super( name, value );
  35832. /**
  35833. * This flag can be used for type testing.
  35834. *
  35835. * @type {boolean}
  35836. * @readonly
  35837. * @default true
  35838. */
  35839. this.isVector4Uniform = true;
  35840. this.boundary = 16;
  35841. this.itemSize = 4;
  35842. }
  35843. }
  35844. /**
  35845. * Represents a Color uniform.
  35846. *
  35847. * @private
  35848. * @augments Uniform
  35849. */
  35850. class ColorUniform extends Uniform {
  35851. /**
  35852. * Constructs a new Number uniform.
  35853. *
  35854. * @param {string} name - The uniform's name.
  35855. * @param {Color} value - The uniform's value.
  35856. */
  35857. constructor( name, value = new Color() ) {
  35858. super( name, value );
  35859. /**
  35860. * This flag can be used for type testing.
  35861. *
  35862. * @type {boolean}
  35863. * @readonly
  35864. * @default true
  35865. */
  35866. this.isColorUniform = true;
  35867. this.boundary = 16;
  35868. this.itemSize = 3;
  35869. }
  35870. }
  35871. /**
  35872. * Represents a Matrix2 uniform.
  35873. *
  35874. * @private
  35875. * @augments Uniform
  35876. */
  35877. class Matrix2Uniform extends Uniform {
  35878. /**
  35879. * Constructs a new Number uniform.
  35880. *
  35881. * @param {string} name - The uniform's name.
  35882. * @param {Matrix2} value - The uniform's value.
  35883. */
  35884. constructor( name, value = new Matrix2() ) {
  35885. super( name, value );
  35886. /**
  35887. * This flag can be used for type testing.
  35888. *
  35889. * @type {boolean}
  35890. * @readonly
  35891. * @default true
  35892. */
  35893. this.isMatrix2Uniform = true;
  35894. this.boundary = 8;
  35895. this.itemSize = 4;
  35896. }
  35897. }
  35898. /**
  35899. * Represents a Matrix3 uniform.
  35900. *
  35901. * @private
  35902. * @augments Uniform
  35903. */
  35904. class Matrix3Uniform extends Uniform {
  35905. /**
  35906. * Constructs a new Number uniform.
  35907. *
  35908. * @param {string} name - The uniform's name.
  35909. * @param {Matrix3} value - The uniform's value.
  35910. */
  35911. constructor( name, value = new Matrix3() ) {
  35912. super( name, value );
  35913. /**
  35914. * This flag can be used for type testing.
  35915. *
  35916. * @type {boolean}
  35917. * @readonly
  35918. * @default true
  35919. */
  35920. this.isMatrix3Uniform = true;
  35921. this.boundary = 48;
  35922. this.itemSize = 12;
  35923. }
  35924. }
  35925. /**
  35926. * Represents a Matrix4 uniform.
  35927. *
  35928. * @private
  35929. * @augments Uniform
  35930. */
  35931. class Matrix4Uniform extends Uniform {
  35932. /**
  35933. * Constructs a new Number uniform.
  35934. *
  35935. * @param {string} name - The uniform's name.
  35936. * @param {Matrix4} value - The uniform's value.
  35937. */
  35938. constructor( name, value = new Matrix4() ) {
  35939. super( name, value );
  35940. /**
  35941. * This flag can be used for type testing.
  35942. *
  35943. * @type {boolean}
  35944. * @readonly
  35945. * @default true
  35946. */
  35947. this.isMatrix4Uniform = true;
  35948. this.boundary = 64;
  35949. this.itemSize = 16;
  35950. }
  35951. }
  35952. /**
  35953. * A special form of Number uniform binding type.
  35954. * It's value is managed by a node object.
  35955. *
  35956. * @private
  35957. * @augments NumberUniform
  35958. */
  35959. class NumberNodeUniform extends NumberUniform {
  35960. /**
  35961. * Constructs a new node-based Number uniform.
  35962. *
  35963. * @param {NodeUniform} nodeUniform - The node uniform.
  35964. */
  35965. constructor( nodeUniform ) {
  35966. super( nodeUniform.name, nodeUniform.value );
  35967. /**
  35968. * The node uniform.
  35969. *
  35970. * @type {NodeUniform}
  35971. */
  35972. this.nodeUniform = nodeUniform;
  35973. }
  35974. /**
  35975. * Overwritten to return the value of the node uniform.
  35976. *
  35977. * @return {number} The value.
  35978. */
  35979. getValue() {
  35980. return this.nodeUniform.value;
  35981. }
  35982. /**
  35983. * Returns the node uniform data type.
  35984. *
  35985. * @return {string} The data type.
  35986. */
  35987. getType() {
  35988. return this.nodeUniform.type;
  35989. }
  35990. }
  35991. /**
  35992. * A special form of Vector2 uniform binding type.
  35993. * It's value is managed by a node object.
  35994. *
  35995. * @private
  35996. * @augments Vector2Uniform
  35997. */
  35998. class Vector2NodeUniform extends Vector2Uniform {
  35999. /**
  36000. * Constructs a new node-based Vector2 uniform.
  36001. *
  36002. * @param {NodeUniform} nodeUniform - The node uniform.
  36003. */
  36004. constructor( nodeUniform ) {
  36005. super( nodeUniform.name, nodeUniform.value );
  36006. /**
  36007. * The node uniform.
  36008. *
  36009. * @type {NodeUniform}
  36010. */
  36011. this.nodeUniform = nodeUniform;
  36012. }
  36013. /**
  36014. * Overwritten to return the value of the node uniform.
  36015. *
  36016. * @return {Vector2} The value.
  36017. */
  36018. getValue() {
  36019. return this.nodeUniform.value;
  36020. }
  36021. /**
  36022. * Returns the node uniform data type.
  36023. *
  36024. * @return {string} The data type.
  36025. */
  36026. getType() {
  36027. return this.nodeUniform.type;
  36028. }
  36029. }
  36030. /**
  36031. * A special form of Vector3 uniform binding type.
  36032. * It's value is managed by a node object.
  36033. *
  36034. * @private
  36035. * @augments Vector3Uniform
  36036. */
  36037. class Vector3NodeUniform extends Vector3Uniform {
  36038. /**
  36039. * Constructs a new node-based Vector3 uniform.
  36040. *
  36041. * @param {NodeUniform} nodeUniform - The node uniform.
  36042. */
  36043. constructor( nodeUniform ) {
  36044. super( nodeUniform.name, nodeUniform.value );
  36045. /**
  36046. * The node uniform.
  36047. *
  36048. * @type {NodeUniform}
  36049. */
  36050. this.nodeUniform = nodeUniform;
  36051. }
  36052. /**
  36053. * Overwritten to return the value of the node uniform.
  36054. *
  36055. * @return {Vector3} The value.
  36056. */
  36057. getValue() {
  36058. return this.nodeUniform.value;
  36059. }
  36060. /**
  36061. * Returns the node uniform data type.
  36062. *
  36063. * @return {string} The data type.
  36064. */
  36065. getType() {
  36066. return this.nodeUniform.type;
  36067. }
  36068. }
  36069. /**
  36070. * A special form of Vector4 uniform binding type.
  36071. * It's value is managed by a node object.
  36072. *
  36073. * @private
  36074. * @augments Vector4Uniform
  36075. */
  36076. class Vector4NodeUniform extends Vector4Uniform {
  36077. /**
  36078. * Constructs a new node-based Vector4 uniform.
  36079. *
  36080. * @param {NodeUniform} nodeUniform - The node uniform.
  36081. */
  36082. constructor( nodeUniform ) {
  36083. super( nodeUniform.name, nodeUniform.value );
  36084. /**
  36085. * The node uniform.
  36086. *
  36087. * @type {NodeUniform}
  36088. */
  36089. this.nodeUniform = nodeUniform;
  36090. }
  36091. /**
  36092. * Overwritten to return the value of the node uniform.
  36093. *
  36094. * @return {Vector4} The value.
  36095. */
  36096. getValue() {
  36097. return this.nodeUniform.value;
  36098. }
  36099. /**
  36100. * Returns the node uniform data type.
  36101. *
  36102. * @return {string} The data type.
  36103. */
  36104. getType() {
  36105. return this.nodeUniform.type;
  36106. }
  36107. }
  36108. /**
  36109. * A special form of Color uniform binding type.
  36110. * It's value is managed by a node object.
  36111. *
  36112. * @private
  36113. * @augments ColorUniform
  36114. */
  36115. class ColorNodeUniform extends ColorUniform {
  36116. /**
  36117. * Constructs a new node-based Color uniform.
  36118. *
  36119. * @param {NodeUniform} nodeUniform - The node uniform.
  36120. */
  36121. constructor( nodeUniform ) {
  36122. super( nodeUniform.name, nodeUniform.value );
  36123. /**
  36124. * The node uniform.
  36125. *
  36126. * @type {NodeUniform}
  36127. */
  36128. this.nodeUniform = nodeUniform;
  36129. }
  36130. /**
  36131. * Overwritten to return the value of the node uniform.
  36132. *
  36133. * @return {Color} The value.
  36134. */
  36135. getValue() {
  36136. return this.nodeUniform.value;
  36137. }
  36138. /**
  36139. * Returns the node uniform data type.
  36140. *
  36141. * @return {string} The data type.
  36142. */
  36143. getType() {
  36144. return this.nodeUniform.type;
  36145. }
  36146. }
  36147. /**
  36148. * A special form of Matrix2 uniform binding type.
  36149. * It's value is managed by a node object.
  36150. *
  36151. * @private
  36152. * @augments Matrix2Uniform
  36153. */
  36154. class Matrix2NodeUniform extends Matrix2Uniform {
  36155. /**
  36156. * Constructs a new node-based Matrix2 uniform.
  36157. *
  36158. * @param {NodeUniform} nodeUniform - The node uniform.
  36159. */
  36160. constructor( nodeUniform ) {
  36161. super( nodeUniform.name, nodeUniform.value );
  36162. /**
  36163. * The node uniform.
  36164. *
  36165. * @type {NodeUniform}
  36166. */
  36167. this.nodeUniform = nodeUniform;
  36168. }
  36169. /**
  36170. * Overwritten to return the value of the node uniform.
  36171. *
  36172. * @return {Matrix2} The value.
  36173. */
  36174. getValue() {
  36175. return this.nodeUniform.value;
  36176. }
  36177. /**
  36178. * Returns the node uniform data type.
  36179. *
  36180. * @return {string} The data type.
  36181. */
  36182. getType() {
  36183. return this.nodeUniform.type;
  36184. }
  36185. }
  36186. /**
  36187. * A special form of Matrix3 uniform binding type.
  36188. * It's value is managed by a node object.
  36189. *
  36190. * @private
  36191. * @augments Matrix3Uniform
  36192. */
  36193. class Matrix3NodeUniform extends Matrix3Uniform {
  36194. /**
  36195. * Constructs a new node-based Matrix3 uniform.
  36196. *
  36197. * @param {NodeUniform} nodeUniform - The node uniform.
  36198. */
  36199. constructor( nodeUniform ) {
  36200. super( nodeUniform.name, nodeUniform.value );
  36201. /**
  36202. * The node uniform.
  36203. *
  36204. * @type {NodeUniform}
  36205. */
  36206. this.nodeUniform = nodeUniform;
  36207. }
  36208. /**
  36209. * Overwritten to return the value of the node uniform.
  36210. *
  36211. * @return {Matrix3} The value.
  36212. */
  36213. getValue() {
  36214. return this.nodeUniform.value;
  36215. }
  36216. /**
  36217. * Returns the node uniform data type.
  36218. *
  36219. * @return {string} The data type.
  36220. */
  36221. getType() {
  36222. return this.nodeUniform.type;
  36223. }
  36224. }
  36225. /**
  36226. * A special form of Matrix4 uniform binding type.
  36227. * It's value is managed by a node object.
  36228. *
  36229. * @private
  36230. * @augments Matrix4Uniform
  36231. */
  36232. class Matrix4NodeUniform extends Matrix4Uniform {
  36233. /**
  36234. * Constructs a new node-based Matrix4 uniform.
  36235. *
  36236. * @param {NodeUniform} nodeUniform - The node uniform.
  36237. */
  36238. constructor( nodeUniform ) {
  36239. super( nodeUniform.name, nodeUniform.value );
  36240. /**
  36241. * The node uniform.
  36242. *
  36243. * @type {NodeUniform}
  36244. */
  36245. this.nodeUniform = nodeUniform;
  36246. }
  36247. /**
  36248. * Overwritten to return the value of the node uniform.
  36249. *
  36250. * @return {Matrix4} The value.
  36251. */
  36252. getValue() {
  36253. return this.nodeUniform.value;
  36254. }
  36255. /**
  36256. * Returns the node uniform data type.
  36257. *
  36258. * @return {string} The data type.
  36259. */
  36260. getType() {
  36261. return this.nodeUniform.type;
  36262. }
  36263. }
  36264. let _id$5 = 0;
  36265. const _bindingGroupsCache = new WeakMap();
  36266. const _functionNodeCache = new WeakMap();
  36267. const sharedNodeData = new WeakMap();
  36268. const typeFromArray = new Map( [
  36269. [ Int8Array, 'int' ],
  36270. [ Int16Array, 'int' ],
  36271. [ Int32Array, 'int' ],
  36272. [ Uint8Array, 'uint' ],
  36273. [ Uint16Array, 'uint' ],
  36274. [ Uint32Array, 'uint' ],
  36275. [ Float32Array, 'float' ]
  36276. ] );
  36277. const _toFloat = ( value ) => {
  36278. if ( /e/g.test( value ) ) {
  36279. return String( value ).replace( /\+/g, '' );
  36280. } else {
  36281. value = Number( value );
  36282. return value + ( value % 1 ? '' : '.0' );
  36283. }
  36284. };
  36285. const _checkWriteUsage = ( data ) => {
  36286. if ( data.writeUsageCount > 0 ) return true;
  36287. if ( data.subBuildsCache !== undefined ) {
  36288. for ( const subBuild in data.subBuildsCache ) {
  36289. if ( _checkWriteUsage( data.subBuildsCache[ subBuild ] ) ) {
  36290. return true;
  36291. }
  36292. }
  36293. }
  36294. return false;
  36295. };
  36296. /**
  36297. * Base class for builders which generate a shader program based
  36298. * on a 3D object and its node material definition.
  36299. */
  36300. class NodeBuilder {
  36301. /**
  36302. * Constructs a new node builder.
  36303. *
  36304. * @param {Object3D} object - The 3D object.
  36305. * @param {Renderer} renderer - The current renderer.
  36306. * @param {NodeParser} parser - A reference to a node parser.
  36307. */
  36308. constructor( object, renderer, parser ) {
  36309. /**
  36310. * The 3D object.
  36311. *
  36312. * @type {Object3D}
  36313. */
  36314. this.object = object;
  36315. /**
  36316. * The material of the 3D object.
  36317. *
  36318. * @type {?Material}
  36319. */
  36320. this.material = ( object && object.material ) || null;
  36321. /**
  36322. * The geometry of the 3D object.
  36323. *
  36324. * @type {?BufferGeometry}
  36325. */
  36326. this.geometry = ( object && object.geometry ) || null;
  36327. /**
  36328. * The current renderer.
  36329. *
  36330. * @type {Renderer}
  36331. */
  36332. this.renderer = renderer;
  36333. /**
  36334. * A reference to a node parser.
  36335. *
  36336. * @type {NodeParser}
  36337. */
  36338. this.parser = parser;
  36339. /**
  36340. * The scene the 3D object belongs to.
  36341. *
  36342. * @type {?Scene}
  36343. * @default null
  36344. */
  36345. this.scene = null;
  36346. /**
  36347. * The camera the 3D object is rendered with.
  36348. *
  36349. * @type {?Camera}
  36350. * @default null
  36351. */
  36352. this.camera = null;
  36353. /**
  36354. * A list of all nodes the builder is processing
  36355. * for this 3D object.
  36356. *
  36357. * @type {Set<Node>}
  36358. */
  36359. this.nodes = new Set();
  36360. /**
  36361. * A list of all nodes the builder is processing in sequential order.
  36362. *
  36363. * This is used to determine the update order of nodes, which is important for
  36364. * {@link NodeUpdateType#UPDATE_BEFORE} and {@link NodeUpdateType#UPDATE_AFTER}.
  36365. *
  36366. * @type {Set<Node>}
  36367. */
  36368. this.sequentialNodes = new Set();
  36369. /**
  36370. * A list of all nodes which {@link Node#update} method should be executed.
  36371. *
  36372. * @type {Array<Node>}
  36373. */
  36374. this.updateNodes = [];
  36375. /**
  36376. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  36377. *
  36378. * @type {Array<Node>}
  36379. */
  36380. this.updateBeforeNodes = [];
  36381. /**
  36382. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  36383. *
  36384. * @type {Array<Node>}
  36385. */
  36386. this.updateAfterNodes = [];
  36387. /**
  36388. * A dictionary that assigns each node to a unique hash.
  36389. *
  36390. * @type {Object<number,Node>}
  36391. */
  36392. this.hashNodes = {};
  36393. /**
  36394. * A reference to a node material observer.
  36395. *
  36396. * @type {?NodeMaterialObserver}
  36397. * @default null
  36398. */
  36399. this.observer = null;
  36400. /**
  36401. * A reference to the current lights node.
  36402. *
  36403. * @type {?LightsNode}
  36404. * @default null
  36405. */
  36406. this.lightsNode = null;
  36407. /**
  36408. * A reference to the current environment node.
  36409. *
  36410. * @type {?Node}
  36411. * @default null
  36412. */
  36413. this.environmentNode = null;
  36414. /**
  36415. * A reference to the current fog node.
  36416. *
  36417. * @type {?Node}
  36418. * @default null
  36419. */
  36420. this.fogNode = null;
  36421. /**
  36422. * The current clipping context.
  36423. *
  36424. * @type {?ClippingContext}
  36425. */
  36426. this.clippingContext = null;
  36427. /**
  36428. * Whether the built material uses hardware clipping or not.
  36429. *
  36430. * @type {boolean}
  36431. * @default false
  36432. */
  36433. this.hardwareClipping = false;
  36434. /**
  36435. * The generated vertex shader.
  36436. *
  36437. * @type {?string}
  36438. */
  36439. this.vertexShader = null;
  36440. /**
  36441. * The generated fragment shader.
  36442. *
  36443. * @type {?string}
  36444. */
  36445. this.fragmentShader = null;
  36446. /**
  36447. * The generated compute shader.
  36448. *
  36449. * @type {?string}
  36450. */
  36451. this.computeShader = null;
  36452. /**
  36453. * Nodes used in the primary flow of code generation.
  36454. *
  36455. * @type {Object<string,Array<Node>>}
  36456. */
  36457. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  36458. /**
  36459. * Nodes code from `.flowNodes`.
  36460. *
  36461. * @type {Object<string,string>}
  36462. */
  36463. this.flowCode = { vertex: '', fragment: '', compute: '' };
  36464. /**
  36465. * This dictionary holds the node uniforms of the builder.
  36466. * The uniforms are maintained in an array for each shader stage.
  36467. *
  36468. * @type {Object}
  36469. */
  36470. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  36471. /**
  36472. * This dictionary holds the output structs of the builder.
  36473. * The structs are maintained in an array for each shader stage.
  36474. *
  36475. * @type {Object}
  36476. */
  36477. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  36478. /**
  36479. * This dictionary holds the types of the builder.
  36480. *
  36481. * @type {Object}
  36482. */
  36483. this.types = { vertex: [], fragment: [], compute: [], index: 0 };
  36484. /**
  36485. * This dictionary holds the bindings for each shader stage.
  36486. *
  36487. * @type {Object}
  36488. */
  36489. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  36490. /**
  36491. * This dictionary maintains the binding indices per bind group.
  36492. *
  36493. * @type {Object}
  36494. */
  36495. this.bindingsIndexes = {};
  36496. /**
  36497. * Reference to the array of bind groups.
  36498. *
  36499. * @type {?Array<BindGroup>}
  36500. */
  36501. this.bindGroups = null;
  36502. /**
  36503. * This array holds the node attributes of this builder
  36504. * created via {@link AttributeNode}.
  36505. *
  36506. * @type {Array<NodeAttribute>}
  36507. */
  36508. this.attributes = [];
  36509. /**
  36510. * This array holds the node attributes of this builder
  36511. * created via {@link BufferAttributeNode}.
  36512. *
  36513. * @type {Array<NodeAttribute>}
  36514. */
  36515. this.bufferAttributes = [];
  36516. /**
  36517. * This array holds the node varyings of this builder.
  36518. *
  36519. * @type {Array<NodeVarying>}
  36520. */
  36521. this.varyings = [];
  36522. /**
  36523. * This dictionary holds the (native) node codes of this builder.
  36524. * The codes are maintained in an array for each shader stage.
  36525. *
  36526. * @type {Object<string,Array<NodeCode>>}
  36527. */
  36528. this.codes = {};
  36529. /**
  36530. * This dictionary holds the node variables of this builder.
  36531. * The variables are maintained in an array for each shader stage.
  36532. * This dictionary is also used to count the number of variables
  36533. * according to their type (const, vars).
  36534. *
  36535. * @type {Object<string,Array<NodeVar>|number>}
  36536. */
  36537. this.vars = {};
  36538. /**
  36539. * This dictionary holds the declarations for each shader stage.
  36540. *
  36541. * @type {Object}
  36542. */
  36543. this.declarations = {};
  36544. /**
  36545. * Current code flow.
  36546. * All code generated in this stack will be stored in `.flow`.
  36547. *
  36548. * @type {{code: string}}
  36549. */
  36550. this.flow = { code: '' };
  36551. /**
  36552. * A chain of nodes.
  36553. * Used to check recursive calls in node-graph.
  36554. *
  36555. * @type {Array<Node>}
  36556. */
  36557. this.chaining = [];
  36558. /**
  36559. * The current stack.
  36560. * This reflects the current process in the code block hierarchy,
  36561. * it is useful to know if the current process is inside a conditional for example.
  36562. *
  36563. * @type {StackNode}
  36564. */
  36565. this.stack = stack();
  36566. /**
  36567. * List of stack nodes.
  36568. * The current stack hierarchy is stored in an array.
  36569. *
  36570. * @type {Array<StackNode>}
  36571. */
  36572. this.stacks = [];
  36573. /**
  36574. * A tab value. Used for shader string generation.
  36575. *
  36576. * @type {string}
  36577. * @default '\t'
  36578. */
  36579. this.tab = '\t';
  36580. /**
  36581. * Reference to the current function node.
  36582. *
  36583. * @type {?FunctionNode}
  36584. * @default null
  36585. */
  36586. this.currentFunctionNode = null;
  36587. /**
  36588. * The builder's context.
  36589. *
  36590. * @type {Object}
  36591. */
  36592. this.context = {
  36593. material: this.material
  36594. };
  36595. /**
  36596. * The builder's cache.
  36597. *
  36598. * @type {NodeCache}
  36599. */
  36600. this.cache = new NodeCache();
  36601. /**
  36602. * Since the {@link NodeBuilder#cache} might be temporarily
  36603. * overwritten by other caches, this member retains the reference
  36604. * to the builder's own cache.
  36605. *
  36606. * @type {NodeCache}
  36607. * @default this.cache
  36608. */
  36609. this.globalCache = this.cache;
  36610. this.flowsData = new WeakMap();
  36611. /**
  36612. * The current shader stage.
  36613. *
  36614. * @type {?('vertex'|'fragment'|'compute'|'any')}
  36615. */
  36616. this.shaderStage = null;
  36617. /**
  36618. * The current build stage.
  36619. *
  36620. * @type {?('setup'|'analyze'|'generate')}
  36621. */
  36622. this.buildStage = null;
  36623. /**
  36624. * The sub-build layers.
  36625. *
  36626. * @type {Array<SubBuildNode>}
  36627. * @default []
  36628. */
  36629. this.subBuildLayers = [];
  36630. /**
  36631. * The active stack nodes.
  36632. *
  36633. * @type {Array<StackNode>}
  36634. */
  36635. this.activeStacks = [];
  36636. /**
  36637. * The current sub-build TSL function(Fn).
  36638. *
  36639. * @type {?string}
  36640. * @default null
  36641. */
  36642. this.subBuildFn = null;
  36643. /**
  36644. * The current TSL function(Fn) call node.
  36645. *
  36646. * @type {?Node}
  36647. * @default null
  36648. */
  36649. this.fnCall = null;
  36650. Object.defineProperty( this, 'id', { value: _id$5 ++ } );
  36651. }
  36652. /**
  36653. * Whether the material is using flat shading or not.
  36654. *
  36655. * @returns {boolean} Whether the material is using flat shading or not.
  36656. */
  36657. isFlatShading() {
  36658. return this.material.flatShading === true || this.geometry.hasAttribute( 'normal' ) === false;
  36659. }
  36660. /**
  36661. * Whether the material is opaque or not.
  36662. *
  36663. * @return {boolean} Whether the material is opaque or not.
  36664. */
  36665. isOpaque() {
  36666. const material = this.material;
  36667. return material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false;
  36668. }
  36669. /**
  36670. * Factory method for creating an instance of {@link RenderTarget} with the given
  36671. * dimensions and options.
  36672. *
  36673. * @param {number} width - The width of the render target.
  36674. * @param {number} height - The height of the render target.
  36675. * @param {Object} options - The options of the render target.
  36676. * @return {RenderTarget} The render target.
  36677. */
  36678. createRenderTarget( width, height, options ) {
  36679. return new RenderTarget( width, height, options );
  36680. }
  36681. /**
  36682. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  36683. * dimensions and options.
  36684. *
  36685. * @param {number} size - The size of the cube render target.
  36686. * @param {Object} options - The options of the cube render target.
  36687. * @return {CubeRenderTarget} The cube render target.
  36688. */
  36689. createCubeRenderTarget( size, options ) {
  36690. return new CubeRenderTarget( size, options );
  36691. }
  36692. /**
  36693. * Whether the given node is included in the internal array of nodes or not.
  36694. *
  36695. * @param {Node} node - The node to test.
  36696. * @return {boolean} Whether the given node is included in the internal array of nodes or not.
  36697. */
  36698. includes( node ) {
  36699. return this.nodes.has( node );
  36700. }
  36701. /**
  36702. * Returns the type of the color output based on the renderer's render target.
  36703. *
  36704. * @param {number} [index=0] - The index of the render target texture.
  36705. * @return {string} The type.
  36706. */
  36707. getOutputType( index = 0 ) {
  36708. const renderTarget = this.renderer.getRenderTarget();
  36709. if ( renderTarget !== null ) {
  36710. return getTextureType( renderTarget.textures[ index ] );
  36711. }
  36712. return 'vec4';
  36713. }
  36714. /**
  36715. * Returns the output struct name which is required by
  36716. * {@link OutputStructNode}.
  36717. *
  36718. * @abstract
  36719. * @return {string} The name of the output struct.
  36720. */
  36721. getOutputStructName() {}
  36722. /**
  36723. * Returns a bind group for the given group name and binding.
  36724. *
  36725. * @private
  36726. * @param {string} groupName - The group name.
  36727. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  36728. * @return {BindGroup} The bind group
  36729. */
  36730. _getBindGroup( groupName, bindings ) {
  36731. const groupNode = bindings[ 0 ].groupNode;
  36732. let sharedGroup = groupNode.shared;
  36733. if ( sharedGroup ) {
  36734. for ( let i = 1; i < bindings.length; i ++ ) {
  36735. if ( groupNode !== bindings[ i ].groupNode ) {
  36736. sharedGroup = false;
  36737. }
  36738. }
  36739. }
  36740. //
  36741. let bindGroup;
  36742. if ( sharedGroup ) {
  36743. let cacheKeyString = '';
  36744. for ( const binding of bindings ) {
  36745. if ( binding.isNodeUniformsGroup ) {
  36746. binding.uniforms.sort( ( a, b ) => a.nodeUniform.node.id - b.nodeUniform.node.id );
  36747. for ( const uniform of binding.uniforms ) {
  36748. cacheKeyString += uniform.nodeUniform.node.id;
  36749. }
  36750. } else {
  36751. cacheKeyString += binding.nodeUniform.id;
  36752. }
  36753. }
  36754. // TODO: Remove this hack ._currentRenderContext
  36755. const currentContext = this.renderer._currentRenderContext || this.renderer; // use renderer as fallback until we have a compute context
  36756. let bindingGroupsCache = _bindingGroupsCache.get( currentContext );
  36757. if ( bindingGroupsCache === undefined ) {
  36758. bindingGroupsCache = new Map();
  36759. _bindingGroupsCache.set( currentContext, bindingGroupsCache );
  36760. }
  36761. //
  36762. const cacheKey = hashString( cacheKeyString );
  36763. bindGroup = bindingGroupsCache.get( cacheKey );
  36764. if ( bindGroup === undefined ) {
  36765. bindGroup = new BindGroup( groupName, bindings );
  36766. bindingGroupsCache.set( cacheKey, bindGroup );
  36767. }
  36768. } else {
  36769. bindGroup = new BindGroup( groupName, bindings );
  36770. }
  36771. return bindGroup;
  36772. }
  36773. /**
  36774. * Returns an array of node uniform groups for the given group name and shader stage.
  36775. *
  36776. * @param {string} groupName - The group name.
  36777. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36778. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  36779. */
  36780. getBindGroupArray( groupName, shaderStage ) {
  36781. const bindings = this.bindings[ shaderStage ];
  36782. let bindGroup = bindings[ groupName ];
  36783. if ( bindGroup === undefined ) {
  36784. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  36785. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  36786. }
  36787. bindings[ groupName ] = bindGroup = [];
  36788. }
  36789. return bindGroup;
  36790. }
  36791. /**
  36792. * Returns a list bindings of all shader stages separated by groups.
  36793. *
  36794. * @return {Array<BindGroup>} The list of bindings.
  36795. */
  36796. getBindings() {
  36797. let bindingsGroups = this.bindGroups;
  36798. if ( bindingsGroups === null ) {
  36799. const groups = {};
  36800. const bindings = this.bindings;
  36801. for ( const shaderStage of shaderStages ) {
  36802. for ( const groupName in bindings[ shaderStage ] ) {
  36803. const uniforms = bindings[ shaderStage ][ groupName ];
  36804. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  36805. for ( const uniform of uniforms ) {
  36806. if ( groupUniforms.includes( uniform ) === false ) {
  36807. groupUniforms.push( uniform );
  36808. }
  36809. }
  36810. }
  36811. }
  36812. bindingsGroups = [];
  36813. for ( const groupName in groups ) {
  36814. const group = groups[ groupName ];
  36815. const bindingsGroup = this._getBindGroup( groupName, group );
  36816. bindingsGroups.push( bindingsGroup );
  36817. }
  36818. this.bindGroups = bindingsGroups;
  36819. }
  36820. return bindingsGroups;
  36821. }
  36822. /**
  36823. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  36824. */
  36825. sortBindingGroups() {
  36826. const bindingsGroups = this.getBindings();
  36827. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  36828. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  36829. const bindingGroup = bindingsGroups[ i ];
  36830. this.bindingsIndexes[ bindingGroup.name ].group = i;
  36831. }
  36832. }
  36833. /**
  36834. * The builder maintains each node in a hash-based dictionary.
  36835. * This method sets the given node (value) with the given hash (key) into this dictionary.
  36836. *
  36837. * @param {Node} node - The node to add.
  36838. * @param {number} hash - The hash of the node.
  36839. */
  36840. setHashNode( node, hash ) {
  36841. this.hashNodes[ hash ] = node;
  36842. }
  36843. /**
  36844. * Adds a node to this builder.
  36845. *
  36846. * @param {Node} node - The node to add.
  36847. */
  36848. addNode( node ) {
  36849. if ( this.nodes.has( node ) === false ) {
  36850. this.nodes.add( node );
  36851. this.setHashNode( node, node.getHash( this ) );
  36852. }
  36853. }
  36854. /**
  36855. * It is used to add Nodes that will be used as FRAME and RENDER events,
  36856. * and need to follow a certain sequence in the calls to work correctly.
  36857. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  36858. *
  36859. * @param {Node} node - The node to add.
  36860. */
  36861. addSequentialNode( node ) {
  36862. const updateBeforeType = node.getUpdateBeforeType();
  36863. const updateAfterType = node.getUpdateAfterType();
  36864. if ( updateBeforeType !== NodeUpdateType.NONE || updateAfterType !== NodeUpdateType.NONE ) {
  36865. this.sequentialNodes.add( node );
  36866. }
  36867. }
  36868. /**
  36869. * Checks the update types of nodes
  36870. */
  36871. buildUpdateNodes() {
  36872. for ( const node of this.nodes ) {
  36873. const updateType = node.getUpdateType();
  36874. if ( updateType !== NodeUpdateType.NONE ) {
  36875. this.updateNodes.push( node );
  36876. }
  36877. }
  36878. for ( const node of this.sequentialNodes ) {
  36879. const updateBeforeType = node.getUpdateBeforeType();
  36880. const updateAfterType = node.getUpdateAfterType();
  36881. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  36882. this.updateBeforeNodes.push( node );
  36883. }
  36884. if ( updateAfterType !== NodeUpdateType.NONE ) {
  36885. this.updateAfterNodes.push( node );
  36886. }
  36887. }
  36888. }
  36889. /**
  36890. * A reference the current node which is the
  36891. * last node in the chain of nodes.
  36892. *
  36893. * @type {Node}
  36894. */
  36895. get currentNode() {
  36896. return this.chaining[ this.chaining.length - 1 ];
  36897. }
  36898. /**
  36899. * Whether the given texture is filtered or not.
  36900. *
  36901. * @param {Texture} texture - The texture to check.
  36902. * @return {boolean} Whether the given texture is filtered or not.
  36903. */
  36904. isFilteredTexture( texture ) {
  36905. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  36906. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  36907. }
  36908. /**
  36909. * Returns the maximum number of bytes available for uniform buffers.
  36910. *
  36911. * @return {number} The maximum number of bytes available for uniform buffers.
  36912. */
  36913. getUniformBufferLimit() {
  36914. return this.renderer.backend.capabilities.getUniformBufferLimit();
  36915. }
  36916. /**
  36917. * Adds the given node to the internal node chain.
  36918. * This is used to check recursive calls in node-graph.
  36919. *
  36920. * @param {Node} node - The node to add.
  36921. */
  36922. addChain( node ) {
  36923. /*
  36924. if ( this.chaining.indexOf( node ) !== - 1 ) {
  36925. warn( 'Recursive node: ', node );
  36926. }
  36927. */
  36928. this.chaining.push( node );
  36929. }
  36930. /**
  36931. * Removes the given node from the internal node chain.
  36932. *
  36933. * @param {Node} node - The node to remove.
  36934. */
  36935. removeChain( node ) {
  36936. const lastChain = this.chaining.pop();
  36937. if ( lastChain !== node ) {
  36938. throw new Error( 'THREE.NodeBuilder: Invalid node chaining!' );
  36939. }
  36940. }
  36941. /**
  36942. * Returns the native shader method name for a given generic name. E.g.
  36943. * the method name `textureDimensions` matches the WGSL name but must be
  36944. * resolved to `textureSize` in GLSL.
  36945. *
  36946. * @abstract
  36947. * @param {string} method - The method name to resolve.
  36948. * @return {string} The resolved method name.
  36949. */
  36950. getMethod( method ) {
  36951. return method;
  36952. }
  36953. /**
  36954. * Returns the native snippet for a ternary operation. E.g. GLSL would output
  36955. * a ternary op as `cond ? x : y` whereas WGSL would output it as `select(y, x, cond)`
  36956. *
  36957. * @abstract
  36958. * @param {string} condSnippet - The condition determining which expression gets resolved.
  36959. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  36960. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  36961. * @return {string} The resolved method name.
  36962. */
  36963. getTernary( /* condSnippet, ifSnippet, elseSnippet*/ ) {
  36964. return null;
  36965. }
  36966. /**
  36967. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  36968. *
  36969. * @param {number} hash - The hash of the node.
  36970. * @return {Node} The found node.
  36971. */
  36972. getNodeFromHash( hash ) {
  36973. return this.hashNodes[ hash ];
  36974. }
  36975. /**
  36976. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  36977. *
  36978. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  36979. * @param {Node} node - The node to add.
  36980. * @return {Node} The node.
  36981. */
  36982. addFlow( shaderStage, node ) {
  36983. this.flowNodes[ shaderStage ].push( node );
  36984. return node;
  36985. }
  36986. /**
  36987. * Sets builder's context.
  36988. *
  36989. * @param {Object} context - The context to set.
  36990. */
  36991. setContext( context ) {
  36992. this.context = context;
  36993. }
  36994. /**
  36995. * Returns the builder's current context.
  36996. *
  36997. * @return {Object} The builder's current context.
  36998. */
  36999. getContext() {
  37000. return this.context;
  37001. }
  37002. /**
  37003. * Adds context data to the builder's current context.
  37004. *
  37005. * @param {Object} context - The context to add.
  37006. * @return {Object} The previous context.
  37007. */
  37008. addContext( context ) {
  37009. const previousContext = this.getContext();
  37010. this.setContext( { ...this.context, ...context } );
  37011. return previousContext;
  37012. }
  37013. /**
  37014. * Gets a context used in shader construction that can be shared across different materials.
  37015. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  37016. *
  37017. * @return {Object} The builder's current context without material.
  37018. */
  37019. getSharedContext() {
  37020. const context = { ...this.context };
  37021. delete context.material;
  37022. delete context.getUV;
  37023. delete context.getOutput;
  37024. delete context.getTextureLevel;
  37025. delete context.getAO;
  37026. delete context.getShadow;
  37027. return context;
  37028. }
  37029. /**
  37030. * Sets builder's cache.
  37031. *
  37032. * @param {NodeCache} cache - The cache to set.
  37033. */
  37034. setCache( cache ) {
  37035. this.cache = cache;
  37036. }
  37037. /**
  37038. * Returns the builder's current cache.
  37039. *
  37040. * @return {NodeCache} The builder's current cache.
  37041. */
  37042. getCache() {
  37043. return this.cache;
  37044. }
  37045. /**
  37046. * Returns a cache for the given node.
  37047. *
  37048. * @param {Node} node - The node.
  37049. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  37050. * @return {NodeCache} The cache.
  37051. */
  37052. getCacheFromNode( node, parent = true ) {
  37053. const data = this.getDataFromNode( node );
  37054. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  37055. return data.cache;
  37056. }
  37057. /**
  37058. * Whether the requested feature is available or not.
  37059. *
  37060. * @abstract
  37061. * @param {string} name - The requested feature.
  37062. * @return {boolean} Whether the requested feature is supported or not.
  37063. */
  37064. isAvailable( /*name*/ ) {
  37065. return false;
  37066. }
  37067. /**
  37068. * Returns the vertexIndex input variable as a native shader string.
  37069. *
  37070. * @abstract
  37071. * @return {string} The instanceIndex shader string.
  37072. */
  37073. getVertexIndex() {
  37074. warn( 'Abstract function.' );
  37075. }
  37076. /**
  37077. * Contextually returns either the vertex stage instance index builtin
  37078. * or the linearized index of an compute invocation within a grid of workgroups.
  37079. *
  37080. * @abstract
  37081. * @return {string} The instanceIndex shader string.
  37082. */
  37083. getInstanceIndex() {
  37084. warn( 'Abstract function.' );
  37085. }
  37086. /**
  37087. * Returns the drawIndex input variable as a native shader string.
  37088. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  37089. *
  37090. * @abstract
  37091. * @return {?string} The drawIndex shader string.
  37092. */
  37093. getDrawIndex() {
  37094. warn( 'Abstract function.' );
  37095. }
  37096. /**
  37097. * Returns the frontFacing input variable as a native shader string.
  37098. *
  37099. * @abstract
  37100. * @return {string} The frontFacing shader string.
  37101. */
  37102. getFrontFacing() {
  37103. warn( 'Abstract function.' );
  37104. }
  37105. /**
  37106. * Returns the fragCoord input variable as a native shader string.
  37107. *
  37108. * @abstract
  37109. * @return {string} The fragCoord shader string.
  37110. */
  37111. getFragCoord() {
  37112. warn( 'Abstract function.' );
  37113. }
  37114. /**
  37115. * Whether to flip texture data along its vertical axis or not. WebGL needs
  37116. * this method evaluate to `true`, WebGPU to `false`.
  37117. *
  37118. * @abstract
  37119. * @return {boolean} Whether to flip texture data along its vertical axis or not.
  37120. */
  37121. isFlipY() {
  37122. return false;
  37123. }
  37124. /**
  37125. * Returns whether the builder is currently in an assignment context.
  37126. *
  37127. * @return {boolean} Whether the builder is in an assignment context.
  37128. */
  37129. isContextAssign() {
  37130. return this.context.assign === true;
  37131. }
  37132. /**
  37133. * Calling this method increases the usage count for the given node by one.
  37134. *
  37135. * @param {Node} node - The node to increase the usage count for.
  37136. * @return {number} The updated usage count.
  37137. */
  37138. increaseUsage( node ) {
  37139. const nodeData = this.getDataFromNode( node );
  37140. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  37141. if ( this.isContextAssign() ) {
  37142. nodeData.writeUsageCount = nodeData.writeUsageCount === undefined ? 1 : nodeData.writeUsageCount + 1;
  37143. } else {
  37144. nodeData.readUsageCount = nodeData.readUsageCount === undefined ? 1 : nodeData.readUsageCount + 1;
  37145. }
  37146. return nodeData.usageCount;
  37147. }
  37148. /**
  37149. * Returns whether the given node has been written to in any shader stage.
  37150. *
  37151. * @param {Node} node - The node to check.
  37152. * @return {boolean} Whether the node has been written to.
  37153. */
  37154. hasWriteUsage( node ) {
  37155. const refNode = node.getShared( this );
  37156. const cache = refNode.isGlobal( this ) ? this.globalCache : this.cache;
  37157. const nodeData = cache.getData( refNode );
  37158. if ( nodeData !== undefined ) {
  37159. for ( const shaderStage in nodeData ) {
  37160. if ( _checkWriteUsage( nodeData[ shaderStage ] ) ) {
  37161. return true;
  37162. }
  37163. }
  37164. }
  37165. return false;
  37166. }
  37167. /**
  37168. * Generates a texture sample shader string for the given texture data.
  37169. *
  37170. * @abstract
  37171. * @param {Texture} texture - The texture.
  37172. * @param {string} textureProperty - The texture property name.
  37173. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  37174. * @return {string} The generated shader string.
  37175. */
  37176. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  37177. warn( 'Abstract function.' );
  37178. }
  37179. /**
  37180. * Generates a texture LOD shader string for the given texture data.
  37181. *
  37182. * @abstract
  37183. * @param {Texture} texture - The texture.
  37184. * @param {string} textureProperty - The texture property name.
  37185. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  37186. * @param {?string} depthSnippet - Snippet defining the 0-based texture array index to sample.
  37187. * @param {string} levelSnippet - Snippet defining the mip level.
  37188. * @return {string} The generated shader string.
  37189. */
  37190. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  37191. warn( 'Abstract function.' );
  37192. }
  37193. /**
  37194. * Generates a texture size shader string for the given texture data.
  37195. *
  37196. * @abstract
  37197. * @param {Texture} texture - The texture.
  37198. * @param {string} textureProperty - The texture property name.
  37199. * @param {string} levelSnippet - Snippet defining the mip level.
  37200. * @return {string} The generated shader string.
  37201. */
  37202. generateTextureSize( /* texture, textureProperty, levelSnippet */ ) {
  37203. warn( 'Abstract function.' );
  37204. }
  37205. /**
  37206. * Generates the array declaration string.
  37207. *
  37208. * @param {string} type - The type.
  37209. * @param {?number} [count] - The count.
  37210. * @return {string} The generated value as a shader string.
  37211. */
  37212. generateArrayDeclaration( type, count ) {
  37213. return this.getType( type ) + '[ ' + count + ' ]';
  37214. }
  37215. /**
  37216. * Generates the array shader string for the given type and value.
  37217. *
  37218. * @param {string} type - The type.
  37219. * @param {?number} [count] - The count.
  37220. * @param {?Array<Node>} [values=null] - The default values.
  37221. * @return {string} The generated value as a shader string.
  37222. */
  37223. generateArray( type, count, values = null ) {
  37224. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  37225. for ( let i = 0; i < count; i ++ ) {
  37226. const value = values ? values[ i ] : null;
  37227. if ( value !== null ) {
  37228. snippet += value.build( this, type );
  37229. } else {
  37230. snippet += this.generateConst( type );
  37231. }
  37232. if ( i < count - 1 ) snippet += ', ';
  37233. }
  37234. snippet += ' )';
  37235. return snippet;
  37236. }
  37237. /**
  37238. * Generates the struct shader string.
  37239. *
  37240. * @param {string} type - The type.
  37241. * @param {Array<Object>} [membersLayout] - The count.
  37242. * @param {?Array<Node>} [values=null] - The default values.
  37243. * @return {string} The generated value as a shader string.
  37244. */
  37245. generateStruct( type, membersLayout, values = null ) {
  37246. const snippets = [];
  37247. for ( const member of membersLayout ) {
  37248. const { name, type } = member;
  37249. if ( values && values[ name ] && values[ name ].isNode ) {
  37250. snippets.push( values[ name ].build( this, type ) );
  37251. } else {
  37252. snippets.push( this.generateConst( type ) );
  37253. }
  37254. }
  37255. return type + '( ' + snippets.join( ', ' ) + ' )';
  37256. }
  37257. /**
  37258. * Generates the shader string for the given type and value.
  37259. *
  37260. * @param {string} type - The type.
  37261. * @param {?any} [value=null] - The value.
  37262. * @return {string} The generated value as a shader string.
  37263. */
  37264. generateConst( type, value = null ) {
  37265. if ( value === null ) {
  37266. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  37267. else if ( type === 'bool' ) value = false;
  37268. else if ( type === 'color' ) value = new Color();
  37269. else if ( type === 'vec2' || type === 'uvec2' || type === 'ivec2' ) value = new Vector2();
  37270. else if ( type === 'vec3' || type === 'uvec3' || type === 'ivec3' ) value = new Vector3();
  37271. else if ( type === 'vec4' || type === 'uvec4' || type === 'ivec4' ) value = new Vector4();
  37272. }
  37273. if ( type === 'float' ) return _toFloat( value );
  37274. if ( type === 'int' ) return `${ Math.round( value ) }`;
  37275. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  37276. if ( type === 'bool' ) return value ? 'true' : 'false';
  37277. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ _toFloat( value.r ) }, ${ _toFloat( value.g ) }, ${ _toFloat( value.b ) } )`;
  37278. const typeLength = this.getTypeLength( type );
  37279. const componentType = this.getComponentType( type );
  37280. const generateConst = value => this.generateConst( componentType, value );
  37281. if ( typeLength === 2 ) {
  37282. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  37283. } else if ( typeLength === 3 ) {
  37284. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  37285. } else if ( typeLength === 4 && type !== 'mat2' ) {
  37286. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  37287. } else if ( typeLength >= 4 && value && ( value.isMatrix2 || value.isMatrix3 || value.isMatrix4 ) ) {
  37288. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  37289. } else if ( typeLength > 4 ) {
  37290. return `${ this.getType( type ) }()`;
  37291. }
  37292. throw new Error( `THREE.NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  37293. }
  37294. /**
  37295. * It might be necessary to convert certain data types to different ones
  37296. * so this method can be used to hide the conversion.
  37297. *
  37298. * @param {string} type - The type.
  37299. * @return {string} The updated type.
  37300. */
  37301. getType( type ) {
  37302. if ( type === 'color' ) return 'vec3';
  37303. return type;
  37304. }
  37305. /**
  37306. * Whether the given attribute name is defined in the geometry or not.
  37307. *
  37308. * @param {string} name - The attribute name.
  37309. * @return {boolean} Whether the given attribute name is defined in the geometry.
  37310. */
  37311. hasGeometryAttribute( name ) {
  37312. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  37313. }
  37314. /**
  37315. * Returns a node attribute for the given name and type.
  37316. *
  37317. * @param {string} name - The attribute's name.
  37318. * @param {string} type - The attribute's type.
  37319. * @return {NodeAttribute} The node attribute.
  37320. */
  37321. getAttribute( name, type ) {
  37322. const attributes = this.attributes;
  37323. // find attribute
  37324. for ( const attribute of attributes ) {
  37325. if ( attribute.name === name ) {
  37326. return attribute;
  37327. }
  37328. }
  37329. // create a new if no exist
  37330. const attribute = new NodeAttribute( name, type );
  37331. this.registerDeclaration( attribute );
  37332. attributes.push( attribute );
  37333. return attribute;
  37334. }
  37335. /**
  37336. * Returns for the given node and shader stage the property name for the shader.
  37337. *
  37338. * @param {Node} node - The node.
  37339. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37340. * @return {string} The property name.
  37341. */
  37342. getPropertyName( node/*, shaderStage*/ ) {
  37343. return node.name;
  37344. }
  37345. /**
  37346. * Returns whether the given name is a reserved keyword of the backend's
  37347. * shading language. Backends override this method to provide their
  37348. * language-specific keywords.
  37349. *
  37350. * @param {string} name - The name to test.
  37351. * @return {boolean} Whether the name is a reserved keyword or not.
  37352. */
  37353. isReservedKeyword( /* name */ ) {
  37354. return false;
  37355. }
  37356. /**
  37357. * Whether the given type is a vector type or not.
  37358. *
  37359. * @param {string} type - The type to check.
  37360. * @return {boolean} Whether the given type is a vector type or not.
  37361. */
  37362. isVector( type ) {
  37363. return /vec\d/.test( type );
  37364. }
  37365. /**
  37366. * Whether the given type is a matrix type or not.
  37367. *
  37368. * @param {string} type - The type to check.
  37369. * @return {boolean} Whether the given type is a matrix type or not.
  37370. */
  37371. isMatrix( type ) {
  37372. return /mat\d/.test( type );
  37373. }
  37374. /**
  37375. * Whether the given type is a reference type or not.
  37376. *
  37377. * @param {string} type - The type to check.
  37378. * @return {boolean} Whether the given type is a reference type or not.
  37379. */
  37380. isReference( type ) {
  37381. return type === 'void' || type === 'property' || type === 'sampler' || type === 'samplerComparison' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  37382. }
  37383. /**
  37384. * Checks if the given texture requires a manual conversion to the working color space.
  37385. *
  37386. * @abstract
  37387. * @param {Texture} texture - The texture to check.
  37388. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  37389. */
  37390. needsToWorkingColorSpace( /*texture*/ ) {
  37391. return false;
  37392. }
  37393. /**
  37394. * Returns the component type of a given texture.
  37395. *
  37396. * @param {Texture} texture - The texture.
  37397. * @return {string} The component type.
  37398. */
  37399. getComponentTypeFromTexture( texture ) {
  37400. const type = texture.type;
  37401. if ( texture.isDepthTexture === true ) return 'float';
  37402. if ( type === IntType ) return 'int';
  37403. if ( type === UnsignedIntType ) return 'uint';
  37404. return 'float';
  37405. }
  37406. /**
  37407. * Returns the element type for a given type.
  37408. *
  37409. * @param {string} type - The type.
  37410. * @return {string} The element type.
  37411. */
  37412. getElementType( type ) {
  37413. if ( type === 'mat2' ) return 'vec2';
  37414. if ( type === 'mat3' ) return 'vec3';
  37415. if ( type === 'mat4' ) return 'vec4';
  37416. return this.getComponentType( type );
  37417. }
  37418. /**
  37419. * Returns the component type for a given type.
  37420. *
  37421. * @param {string} type - The type.
  37422. * @return {string} The component type.
  37423. */
  37424. getComponentType( type ) {
  37425. type = this.getVectorType( type );
  37426. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  37427. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  37428. if ( componentType === null ) return null;
  37429. if ( componentType[ 1 ] === 'b' ) return 'bool';
  37430. if ( componentType[ 1 ] === 'i' ) return 'int';
  37431. if ( componentType[ 1 ] === 'u' ) return 'uint';
  37432. return 'float';
  37433. }
  37434. /**
  37435. * Returns the vector type for a given type.
  37436. *
  37437. * @param {string} type - The type.
  37438. * @return {string} The vector type.
  37439. */
  37440. getVectorType( type ) {
  37441. if ( type === 'color' ) return 'vec3';
  37442. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  37443. return type;
  37444. }
  37445. /**
  37446. * Returns the data type for the given the length and component type.
  37447. *
  37448. * @param {number} length - The length.
  37449. * @param {string} [componentType='float'] - The component type.
  37450. * @return {string} The type.
  37451. */
  37452. getTypeFromLength( length, componentType = 'float' ) {
  37453. if ( length === 1 ) return componentType;
  37454. let baseType = getTypeFromLength( length );
  37455. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  37456. // fix edge case for mat2x2 being same size as vec4
  37457. if ( /mat2/.test( componentType ) === true ) {
  37458. baseType = baseType.replace( 'vec', 'mat' );
  37459. }
  37460. return prefix + baseType;
  37461. }
  37462. /**
  37463. * Returns the type for a given typed array.
  37464. *
  37465. * @param {TypedArray} array - The typed array.
  37466. * @return {string} The type.
  37467. */
  37468. getTypeFromArray( array ) {
  37469. return typeFromArray.get( array.constructor );
  37470. }
  37471. /**
  37472. * Returns the type is an integer type.
  37473. *
  37474. * @param {string} type - The type.
  37475. * @return {boolean} Whether the type is an integer type or not.
  37476. */
  37477. isInteger( type ) {
  37478. return /int|uint|(i|u)vec/.test( type );
  37479. }
  37480. /**
  37481. * Returns the type for a given buffer attribute.
  37482. *
  37483. * @param {BufferAttribute} attribute - The buffer attribute.
  37484. * @return {string} The type.
  37485. */
  37486. getTypeFromAttribute( attribute ) {
  37487. let dataAttribute = attribute;
  37488. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  37489. const array = dataAttribute.array;
  37490. const itemSize = attribute.itemSize;
  37491. const normalized = attribute.normalized;
  37492. let arrayType;
  37493. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  37494. arrayType = this.getTypeFromArray( array );
  37495. }
  37496. return this.getTypeFromLength( itemSize, arrayType );
  37497. }
  37498. /**
  37499. * Returns the length for the given data type.
  37500. *
  37501. * @param {string} type - The data type.
  37502. * @return {number} The length.
  37503. */
  37504. getTypeLength( type ) {
  37505. const vecType = this.getVectorType( type );
  37506. const vecNum = /vec([2-4])/.exec( vecType );
  37507. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  37508. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  37509. if ( /mat2/.test( type ) === true ) return 4;
  37510. if ( /mat3/.test( type ) === true ) return 9;
  37511. if ( /mat4/.test( type ) === true ) return 16;
  37512. return 0;
  37513. }
  37514. /**
  37515. * Returns the vector type for a given matrix type.
  37516. *
  37517. * @param {string} type - The matrix type.
  37518. * @return {string} The vector type.
  37519. */
  37520. getVectorFromMatrix( type ) {
  37521. return type.replace( 'mat', 'vec' );
  37522. }
  37523. /**
  37524. * For a given type this method changes the component type to the
  37525. * given value. E.g. `vec4` should be changed to the new component type
  37526. * `uint` which results in `uvec4`.
  37527. *
  37528. * @param {string} type - The type.
  37529. * @param {string} newComponentType - The new component type.
  37530. * @return {string} The new type.
  37531. */
  37532. changeComponentType( type, newComponentType ) {
  37533. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  37534. }
  37535. /**
  37536. * Returns the integer type pendant for the given type.
  37537. *
  37538. * @param {string} type - The type.
  37539. * @return {string} The integer type.
  37540. */
  37541. getIntegerType( type ) {
  37542. const componentType = this.getComponentType( type );
  37543. if ( componentType === 'int' || componentType === 'uint' ) return type;
  37544. return this.changeComponentType( type, 'int' );
  37545. }
  37546. /**
  37547. * Adds an active stack to the internal stack.
  37548. *
  37549. * @param {StackNode} stack - The stack node to add.
  37550. */
  37551. setActiveStack( stack ) {
  37552. this.activeStacks.push( stack );
  37553. }
  37554. /**
  37555. * Removes the active stack from the internal stack.
  37556. *
  37557. * @param {StackNode} stack - The stack node to remove.
  37558. */
  37559. removeActiveStack( stack ) {
  37560. if ( this.activeStacks[ this.activeStacks.length - 1 ] === stack ) {
  37561. this.activeStacks.pop();
  37562. } else {
  37563. throw new Error( 'THREE.NodeBuilder: Invalid active stack removal.' );
  37564. }
  37565. }
  37566. /**
  37567. * Returns the active stack.
  37568. *
  37569. * @return {StackNode} The active stack.
  37570. */
  37571. getActiveStack() {
  37572. return this.activeStacks[ this.activeStacks.length - 1 ];
  37573. }
  37574. /**
  37575. * Returns the base stack.
  37576. *
  37577. * @return {StackNode} The base stack.
  37578. */
  37579. getBaseStack() {
  37580. return this.activeStacks[ 0 ];
  37581. }
  37582. /**
  37583. * Adds a stack node to the internal stack.
  37584. *
  37585. * @return {StackNode} The added stack node.
  37586. */
  37587. addStack() {
  37588. this.stack = stack( this.stack );
  37589. const previousStack = getCurrentStack();
  37590. this.stacks.push( previousStack );
  37591. setCurrentStack( this.stack );
  37592. return this.stack;
  37593. }
  37594. /**
  37595. * Removes the last stack node from the internal stack.
  37596. *
  37597. * @return {StackNode} The removed stack node.
  37598. */
  37599. removeStack() {
  37600. const lastStack = this.stack;
  37601. for ( const node of lastStack.nodes ) {
  37602. const nodeData = this.getDataFromNode( node );
  37603. nodeData.stack = lastStack;
  37604. }
  37605. this.stack = lastStack.parent;
  37606. setCurrentStack( this.stacks.pop() );
  37607. return lastStack;
  37608. }
  37609. /**
  37610. * The builder maintains (cached) data for each node during the building process. This method
  37611. * can be used to get these data for a specific shader stage and cache.
  37612. *
  37613. * @param {Node} node - The node to get the data for.
  37614. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  37615. * @param {?NodeCache} cache - An optional cache.
  37616. * @return {Object} The node data.
  37617. */
  37618. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  37619. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  37620. let nodeData = cache.getData( node );
  37621. if ( nodeData === undefined ) {
  37622. nodeData = {};
  37623. cache.setData( node, nodeData );
  37624. }
  37625. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  37626. //
  37627. let data = nodeData[ shaderStage ];
  37628. if ( this.subBuildLayers.length === 0 ) return data;
  37629. const subBuilds = nodeData.any ? nodeData.any.subBuilds : null;
  37630. const subBuild = this.getClosestSubBuild( subBuilds );
  37631. if ( subBuild ) {
  37632. if ( data.subBuildsCache === undefined ) data.subBuildsCache = {};
  37633. data = data.subBuildsCache[ subBuild ] || ( data.subBuildsCache[ subBuild ] = {} );
  37634. data.subBuilds = subBuilds;
  37635. }
  37636. return data;
  37637. }
  37638. /**
  37639. * Returns the properties for the given node and shader stage.
  37640. *
  37641. * Properties are typically used within a build stage to reference a node's
  37642. * child node or nodes manually assigned to the properties in a separate build stage.
  37643. * A typical usage pattern for defining nodes manually would be assigning dependency nodes
  37644. * to the current node's properties in the setup stage and building those properties in the generate stage.
  37645. *
  37646. * @param {Node} node - The node to get the properties for.
  37647. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  37648. * @return {Object} The node properties.
  37649. */
  37650. getNodeProperties( node, shaderStage = 'any' ) {
  37651. const nodeData = this.getDataFromNode( node, shaderStage );
  37652. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  37653. }
  37654. /**
  37655. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  37656. *
  37657. * @param {BufferAttributeNode} node - The buffer attribute node.
  37658. * @param {string} type - The node type.
  37659. * @param {?string} [name=null] - The name of the buffer attribute.
  37660. * @return {NodeAttribute} The node attribute.
  37661. */
  37662. getBufferAttributeFromNode( node, type, name = null ) {
  37663. const nodeData = this.getDataFromNode( node, 'vertex' );
  37664. let bufferAttribute = nodeData.bufferAttribute;
  37665. if ( bufferAttribute === undefined ) {
  37666. const index = this.uniforms.index ++;
  37667. if ( name === null ) {
  37668. name = 'nodeAttribute' + index;
  37669. }
  37670. bufferAttribute = new NodeAttribute( name, type, node );
  37671. this.bufferAttributes.push( bufferAttribute );
  37672. nodeData.bufferAttribute = bufferAttribute;
  37673. }
  37674. return bufferAttribute;
  37675. }
  37676. /**
  37677. * Returns an instance of {@link StructType} for the given struct name and shader stage
  37678. * or null if not found.
  37679. *
  37680. * @param {string} name - The name of the struct.
  37681. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  37682. * @return {?StructType} The struct type or null if not found.
  37683. */
  37684. getStructTypeNode( name, shaderStage = this.shaderStage ) {
  37685. return this.types[ shaderStage ][ name ] || null;
  37686. }
  37687. /**
  37688. * Returns an instance of {@link StructType} for the given output struct node.
  37689. *
  37690. * @param {OutputStructNode} node - The output struct node.
  37691. * @param {Array<Object>} membersLayout - The output struct types.
  37692. * @param {?string} [name=null] - The name of the struct.
  37693. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  37694. * @return {StructType} The struct type attribute.
  37695. */
  37696. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  37697. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  37698. let structType = nodeData.structType;
  37699. if ( structType === undefined ) {
  37700. const index = this.structs.index ++;
  37701. if ( name === null ) name = 'StructType' + index;
  37702. structType = new StructType( name, membersLayout );
  37703. this.structs[ shaderStage ].push( structType );
  37704. this.types[ shaderStage ][ name ] = node;
  37705. nodeData.structType = structType;
  37706. }
  37707. return structType;
  37708. }
  37709. /**
  37710. * Returns an instance of {@link StructType} for the given output struct node.
  37711. *
  37712. * @param {OutputStructNode} node - The output struct node.
  37713. * @param {Array<Object>} membersLayout - The output struct types.
  37714. * @return {StructType} The struct type attribute.
  37715. */
  37716. getOutputStructTypeFromNode( node, membersLayout ) {
  37717. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  37718. structType.output = true;
  37719. return structType;
  37720. }
  37721. /**
  37722. * Returns an instance of {@link NodeUniform} for the given uniform node.
  37723. *
  37724. * @param {UniformNode} node - The uniform node.
  37725. * @param {string} type - The uniform type.
  37726. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  37727. * @param {?string} name - The name of the uniform.
  37728. * @return {NodeUniform} The node uniform.
  37729. */
  37730. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  37731. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  37732. let nodeUniform = nodeData.uniform;
  37733. if ( nodeUniform === undefined ) {
  37734. const index = this.uniforms.index ++;
  37735. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  37736. this.uniforms[ shaderStage ].push( nodeUniform );
  37737. this.registerDeclaration( nodeUniform );
  37738. nodeData.uniform = nodeUniform;
  37739. }
  37740. return nodeUniform;
  37741. }
  37742. /**
  37743. * Returns an instance of {@link NodeVar} for the given variable node.
  37744. *
  37745. * @param {VarNode} node - The variable node.
  37746. * @param {?string} name - The variable's name.
  37747. * @param {string} [type=node.getNodeType( this )] - The variable's type.
  37748. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  37749. * @param {boolean} [readOnly=false] - Whether the variable is read-only or not.
  37750. *
  37751. * @return {NodeVar} The node variable.
  37752. */
  37753. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  37754. const nodeData = this.getDataFromNode( node, shaderStage );
  37755. const subBuildVariable = this.getSubBuildProperty( 'variable', nodeData.subBuilds );
  37756. let nodeVar = nodeData[ subBuildVariable ];
  37757. if ( nodeVar === undefined ) {
  37758. const idNS = readOnly ? '_const' : '_var';
  37759. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  37760. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  37761. if ( name === null ) {
  37762. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  37763. this.vars[ idNS ] ++;
  37764. }
  37765. //
  37766. if ( subBuildVariable !== 'variable' ) {
  37767. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  37768. }
  37769. //
  37770. const count = node.getArrayCount( this );
  37771. nodeVar = new NodeVar( name, type, readOnly, count );
  37772. if ( ! readOnly ) {
  37773. vars.push( nodeVar );
  37774. }
  37775. this.registerDeclaration( nodeVar );
  37776. nodeData[ subBuildVariable ] = nodeVar;
  37777. }
  37778. return nodeVar;
  37779. }
  37780. /**
  37781. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  37782. *
  37783. * @param {Node} node - The varying node.
  37784. * @return {boolean} Returns true if deterministic.
  37785. */
  37786. isDeterministic( node ) {
  37787. if ( node.isMathNode ) {
  37788. return this.isDeterministic( node.aNode ) &&
  37789. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  37790. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  37791. } else if ( node.isOperatorNode ) {
  37792. return this.isDeterministic( node.aNode ) &&
  37793. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  37794. } else if ( node.isArrayNode ) {
  37795. if ( node.values !== null ) {
  37796. for ( const n of node.values ) {
  37797. if ( ! this.isDeterministic( n ) ) {
  37798. return false;
  37799. }
  37800. }
  37801. }
  37802. return true;
  37803. } else if ( node.isConstNode ) {
  37804. return true;
  37805. }
  37806. return false;
  37807. }
  37808. /**
  37809. * Returns an instance of {@link NodeVarying} for the given varying node.
  37810. *
  37811. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  37812. * @param {?string} name - The varying's name.
  37813. * @param {string} [type=node.getNodeType( this )] - The varying's type.
  37814. * @param {?string} interpolationType - The interpolation type of the varying.
  37815. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  37816. * @return {NodeVar} The node varying.
  37817. */
  37818. getVaryingFromNode( node, name = null, type = node.getNodeType( this ), interpolationType = null, interpolationSampling = null ) {
  37819. const nodeData = this.getDataFromNode( node, 'any' );
  37820. const subBuildVarying = this.getSubBuildProperty( 'varying', nodeData.subBuilds );
  37821. let nodeVarying = nodeData[ subBuildVarying ];
  37822. if ( nodeVarying === undefined ) {
  37823. const varyings = this.varyings;
  37824. const index = varyings.length;
  37825. if ( name === null ) name = 'nodeVarying' + index;
  37826. //
  37827. if ( subBuildVarying !== 'varying' ) {
  37828. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  37829. }
  37830. //
  37831. nodeVarying = new NodeVarying( name, type, interpolationType, interpolationSampling );
  37832. varyings.push( nodeVarying );
  37833. this.registerDeclaration( nodeVarying );
  37834. nodeData[ subBuildVarying ] = nodeVarying;
  37835. }
  37836. return nodeVarying;
  37837. }
  37838. /**
  37839. * Registers a node declaration in the current shader stage.
  37840. *
  37841. * @param {Object} node - The node to be registered.
  37842. */
  37843. registerDeclaration( node ) {
  37844. const shaderStage = this.shaderStage;
  37845. const declarations = this.declarations[ shaderStage ] || ( this.declarations[ shaderStage ] = {} );
  37846. const checkKeywords = this.renderer.debug.diagnostics.keywords;
  37847. const baseName = node.name;
  37848. let name = baseName;
  37849. let property = this.getPropertyName( node );
  37850. let index = 1;
  37851. // Automatically renames the property if the name is already in use or reserved.
  37852. while ( ( checkKeywords && this.isReservedKeyword( name ) ) || declarations[ property ] !== undefined ) {
  37853. name = baseName + '_' + index ++;
  37854. node.name = name;
  37855. property = this.getPropertyName( node );
  37856. }
  37857. if ( name !== baseName ) {
  37858. warn( `TSL: Declaration name '${ baseName }' of '${ node.type }' is a reserved keyword or already in use. Renamed to '${ name }'.` );
  37859. }
  37860. declarations[ property ] = node;
  37861. }
  37862. /**
  37863. * Returns an instance of {@link NodeCode} for the given code node.
  37864. *
  37865. * @param {CodeNode} node - The code node.
  37866. * @param {string} type - The node type.
  37867. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  37868. * @return {NodeCode} The node code.
  37869. */
  37870. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  37871. const nodeData = this.getDataFromNode( node );
  37872. let nodeCode = nodeData.code;
  37873. if ( nodeCode === undefined ) {
  37874. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  37875. const index = codes.length;
  37876. nodeCode = new NodeCode( 'nodeCode' + index, type );
  37877. codes.push( nodeCode );
  37878. nodeData.code = nodeCode;
  37879. }
  37880. return nodeCode;
  37881. }
  37882. /**
  37883. * Adds a code flow based on the code-block hierarchy.
  37884. * This is used so that code-blocks like If,Else create their variables locally if the Node
  37885. * is only used inside one of these conditionals in the current shader stage.
  37886. *
  37887. * @param {Node} node - The node to add.
  37888. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  37889. */
  37890. addFlowCodeHierarchy( node, nodeBlock ) {
  37891. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  37892. let needsFlowCode = true;
  37893. let nodeBlockHierarchy = nodeBlock;
  37894. while ( nodeBlockHierarchy ) {
  37895. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  37896. needsFlowCode = false;
  37897. break;
  37898. }
  37899. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  37900. }
  37901. if ( needsFlowCode ) {
  37902. for ( const flowCode of flowCodes ) {
  37903. this.addLineFlowCode( flowCode );
  37904. }
  37905. }
  37906. }
  37907. /**
  37908. * Add a inline-code to the current flow code-block.
  37909. *
  37910. * @param {Node} node - The node to add.
  37911. * @param {string} code - The code to add.
  37912. * @param {Node} nodeBlock - Current ConditionalNode
  37913. */
  37914. addLineFlowCodeBlock( node, code, nodeBlock ) {
  37915. const nodeData = this.getDataFromNode( node );
  37916. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  37917. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  37918. flowCodes.push( code );
  37919. codeBlock.set( nodeBlock, true );
  37920. }
  37921. /**
  37922. * Add a inline-code to the current flow.
  37923. *
  37924. * @param {string} code - The code to add.
  37925. * @param {?Node} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  37926. * @return {NodeBuilder} A reference to this node builder.
  37927. */
  37928. addLineFlowCode( code, node = null ) {
  37929. if ( code === '' ) return this;
  37930. if ( node !== null && this.context.nodeBlock ) {
  37931. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  37932. }
  37933. code = this.tab + code;
  37934. if ( ! /;\s*$/.test( code ) ) {
  37935. code = code + ';\n';
  37936. }
  37937. this.flow.code += code;
  37938. return this;
  37939. }
  37940. /**
  37941. * Adds a code to the current code flow.
  37942. *
  37943. * @param {string} code - Shader code.
  37944. * @return {NodeBuilder} A reference to this node builder.
  37945. */
  37946. addFlowCode( code ) {
  37947. this.flow.code += code;
  37948. return this;
  37949. }
  37950. /**
  37951. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  37952. * Typically used in codes with If,Else.
  37953. *
  37954. * @return {NodeBuilder} A reference to this node builder.
  37955. */
  37956. addFlowTab() {
  37957. this.tab += '\t';
  37958. return this;
  37959. }
  37960. /**
  37961. * Removes a tab.
  37962. *
  37963. * @return {NodeBuilder} A reference to this node builder.
  37964. */
  37965. removeFlowTab() {
  37966. this.tab = this.tab.slice( 0, -1 );
  37967. return this;
  37968. }
  37969. /**
  37970. * Gets the current flow data based on a Node.
  37971. *
  37972. * @param {Node} node - Node that the flow was started.
  37973. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37974. * @return {Object} The flow data.
  37975. */
  37976. getFlowData( node/*, shaderStage*/ ) {
  37977. return this.flowsData.get( node );
  37978. }
  37979. /**
  37980. * Executes the node flow based on a root node to generate the final shader code.
  37981. *
  37982. * @param {Node} node - The node to execute.
  37983. * @return {Object} The code flow.
  37984. */
  37985. flowNode( node ) {
  37986. const output = node.getNodeType( this );
  37987. const flowData = this.flowChildNode( node, output );
  37988. this.flowsData.set( node, flowData );
  37989. return flowData;
  37990. }
  37991. /**
  37992. * Includes a node in the current function node.
  37993. *
  37994. * @param {Node} node - The node to include.
  37995. * @returns {void}
  37996. */
  37997. addInclude( node ) {
  37998. if ( this.currentFunctionNode !== null ) {
  37999. this.currentFunctionNode.includes.push( node );
  38000. }
  38001. }
  38002. /**
  38003. * Returns the native shader operator name for a given generic name.
  38004. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  38005. *
  38006. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  38007. * @return {FunctionNode} The build function node.
  38008. */
  38009. buildFunctionNode( shaderNode ) {
  38010. const backend = this.renderer.backend;
  38011. let cache = _functionNodeCache.get( backend );
  38012. if ( cache === undefined ) {
  38013. cache = new WeakMap();
  38014. _functionNodeCache.set( backend, cache );
  38015. }
  38016. let fn = cache.get( shaderNode );
  38017. if ( fn === undefined ) {
  38018. fn = new FunctionNode();
  38019. const previous = this.currentFunctionNode;
  38020. this.currentFunctionNode = fn;
  38021. fn.code = this.buildFunctionCode( shaderNode );
  38022. this.currentFunctionNode = previous;
  38023. cache.set( shaderNode, fn );
  38024. }
  38025. return fn;
  38026. }
  38027. /**
  38028. * Generates a code flow based on a TSL function: Fn().
  38029. *
  38030. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  38031. * @return {Object}
  38032. */
  38033. flowShaderNode( shaderNode ) {
  38034. const layout = shaderNode.layout;
  38035. const inputs = {
  38036. [ Symbol.iterator ]() {
  38037. let index = 0;
  38038. const values = Object.values( this );
  38039. return {
  38040. next: () => ( {
  38041. value: values[ index ],
  38042. done: index ++ >= values.length
  38043. } )
  38044. };
  38045. }
  38046. };
  38047. for ( const input of layout.inputs ) {
  38048. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  38049. }
  38050. //
  38051. shaderNode.layout = null;
  38052. const callNode = shaderNode.call( inputs );
  38053. const flowData = this.flowStagesNode( callNode, layout.type );
  38054. shaderNode.layout = layout;
  38055. return flowData;
  38056. }
  38057. /**
  38058. * Executes the node in a specific build stage.
  38059. *
  38060. * This function can be used to arbitrarily execute the specified build stage
  38061. * outside of the standard build process. For instance, if a node's type depends
  38062. * on properties created by the 'setup' stage, then flowBuildStage(node, 'setup')
  38063. * can be used to execute the setup build stage and access its generated nodes
  38064. * before the standard build process begins.
  38065. *
  38066. * @param {Node} node - The node to execute.
  38067. * @param {string} buildStage - The build stage to execute the node in.
  38068. * @param {?(Node|string)} [output=null] - Expected output type. For example 'vec3'.
  38069. * @return {?(Node|string)} The result of the node build.
  38070. */
  38071. flowBuildStage( node, buildStage, output = null ) {
  38072. const previousBuildStage = this.getBuildStage();
  38073. this.setBuildStage( buildStage );
  38074. const result = node.build( this, output );
  38075. this.setBuildStage( previousBuildStage );
  38076. return result;
  38077. }
  38078. /**
  38079. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  38080. *
  38081. * @param {Node} node - The node to execute.
  38082. * @param {?string} output - Expected output type. For example 'vec3'.
  38083. * @return {Object}
  38084. */
  38085. flowStagesNode( node, output = null ) {
  38086. const previousFlow = this.flow;
  38087. const previousVars = this.vars;
  38088. const previousDeclarations = this.declarations;
  38089. const previousCache = this.cache;
  38090. const previousBuildStage = this.buildStage;
  38091. const previousStack = this.stack;
  38092. const flow = {
  38093. code: ''
  38094. };
  38095. this.flow = flow;
  38096. this.vars = {};
  38097. this.declarations = {};
  38098. this.cache = new NodeCache();
  38099. this.stack = stack();
  38100. for ( const buildStage of defaultBuildStages ) {
  38101. this.setBuildStage( buildStage );
  38102. flow.result = node.build( this, output );
  38103. }
  38104. flow.vars = this.getVars( this.shaderStage );
  38105. this.flow = previousFlow;
  38106. this.vars = previousVars;
  38107. this.declarations = previousDeclarations;
  38108. this.cache = previousCache;
  38109. this.stack = previousStack;
  38110. this.setBuildStage( previousBuildStage );
  38111. return flow;
  38112. }
  38113. /**
  38114. * Returns the native shader operator name for a given generic name.
  38115. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  38116. *
  38117. * @abstract
  38118. * @param {string} op - The operator name to resolve.
  38119. * @return {?string} The resolved operator name.
  38120. */
  38121. getFunctionOperator( /* op */ ) {
  38122. return null;
  38123. }
  38124. /**
  38125. * Builds the given shader node.
  38126. *
  38127. * @abstract
  38128. * @param {ShaderNodeInternal} shaderNode - The shader node.
  38129. * @return {string} The function code.
  38130. */
  38131. buildFunctionCode( /* shaderNode */ ) {
  38132. warn( 'Abstract function.' );
  38133. }
  38134. /**
  38135. * Generates a code flow based on a child Node.
  38136. *
  38137. * @param {Node} node - The node to execute.
  38138. * @param {?string} output - Expected output type. For example 'vec3'.
  38139. * @return {Object} The code flow.
  38140. */
  38141. flowChildNode( node, output = null ) {
  38142. const previousFlow = this.flow;
  38143. const flow = {
  38144. code: ''
  38145. };
  38146. this.flow = flow;
  38147. flow.result = node.build( this, output );
  38148. this.flow = previousFlow;
  38149. return flow;
  38150. }
  38151. /**
  38152. * Executes a flow of code in a different stage.
  38153. *
  38154. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  38155. * return the value in fragment-stage even if it is being executed in an input fragment.
  38156. *
  38157. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  38158. * @param {Node} node - The node to execute.
  38159. * @param {?string} output - Expected output type. For example 'vec3'.
  38160. * @param {?string} propertyName - The property name to assign the result.
  38161. * @return {?(Object|Node)} The code flow or node.build() result.
  38162. */
  38163. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  38164. const previousTab = this.tab;
  38165. const previousCache = this.cache;
  38166. const previousShaderStage = this.shaderStage;
  38167. const previousContext = this.context;
  38168. this.setShaderStage( shaderStage );
  38169. const context = { ...this.context };
  38170. delete context.nodeBlock;
  38171. this.cache = this.globalCache;
  38172. this.tab = '\t';
  38173. this.context = context;
  38174. let result = null;
  38175. if ( this.buildStage === 'generate' ) {
  38176. const flowData = this.flowChildNode( node, output );
  38177. if ( propertyName !== null ) {
  38178. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  38179. }
  38180. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  38181. result = flowData;
  38182. } else {
  38183. result = node.build( this );
  38184. }
  38185. this.setShaderStage( previousShaderStage );
  38186. this.cache = previousCache;
  38187. this.tab = previousTab;
  38188. this.context = previousContext;
  38189. return result;
  38190. }
  38191. /**
  38192. * Returns an array holding all node attributes of this node builder.
  38193. *
  38194. * @return {Array<NodeAttribute>} The node attributes of this builder.
  38195. */
  38196. getAttributesArray() {
  38197. return this.attributes.concat( this.bufferAttributes );
  38198. }
  38199. /**
  38200. * Returns the attribute definitions as a shader string for the given shader stage.
  38201. *
  38202. * @abstract
  38203. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  38204. * @return {string} The attribute code section.
  38205. */
  38206. getAttributes( /*shaderStage*/ ) {
  38207. warn( 'Abstract function.' );
  38208. }
  38209. /**
  38210. * Returns the varying definitions as a shader string for the given shader stage.
  38211. *
  38212. * @abstract
  38213. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  38214. * @return {string} The varying code section.
  38215. */
  38216. getVaryings( /*shaderStage*/ ) {
  38217. warn( 'Abstract function.' );
  38218. }
  38219. /**
  38220. * Returns a single variable definition as a shader string for the given variable type and name.
  38221. *
  38222. * @param {string} type - The variable's type.
  38223. * @param {string} name - The variable's name.
  38224. * @param {?number} [count=null] - The array length.
  38225. * @return {string} The shader string.
  38226. */
  38227. getVar( type, name, count = null ) {
  38228. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  38229. }
  38230. /**
  38231. * Returns the variable definitions as a shader string for the given shader stage.
  38232. *
  38233. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  38234. * @param {boolean} [global=false] - Whether the variables are global.
  38235. * @return {string} The variable code section.
  38236. */
  38237. getVars( shaderStage, global = false ) {
  38238. const snippets = [];
  38239. const vars = this.vars[ shaderStage ];
  38240. if ( vars !== undefined ) {
  38241. for ( const variable of vars ) {
  38242. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  38243. }
  38244. }
  38245. return snippets.join( global ? '\n' : '\n\t' );
  38246. }
  38247. /**
  38248. * Returns the uniform definitions as a shader string for the given shader stage.
  38249. *
  38250. * @abstract
  38251. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  38252. * @return {string} The uniform code section.
  38253. */
  38254. getUniforms( /*shaderStage*/ ) {
  38255. warn( 'Abstract function.' );
  38256. }
  38257. /**
  38258. * Returns the native code definitions as a shader string for the given shader stage.
  38259. *
  38260. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  38261. * @return {string} The native code section.
  38262. */
  38263. getCodes( shaderStage ) {
  38264. const codes = this.codes[ shaderStage ];
  38265. let code = '';
  38266. if ( codes !== undefined ) {
  38267. for ( const nodeCode of codes ) {
  38268. code += nodeCode.code + '\n';
  38269. }
  38270. }
  38271. return code;
  38272. }
  38273. /**
  38274. * Returns the hash of this node builder.
  38275. *
  38276. * @return {string} The hash.
  38277. */
  38278. getHash() {
  38279. return this.vertexShader + this.fragmentShader + this.computeShader;
  38280. }
  38281. /**
  38282. * Sets the current shader stage.
  38283. *
  38284. * @param {?('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage to set.
  38285. */
  38286. setShaderStage( shaderStage ) {
  38287. this.shaderStage = shaderStage;
  38288. }
  38289. /**
  38290. * Returns the current shader stage.
  38291. *
  38292. * @return {?('vertex'|'fragment'|'compute'|'any')} The current shader stage.
  38293. */
  38294. getShaderStage() {
  38295. return this.shaderStage;
  38296. }
  38297. /**
  38298. * Sets the current build stage.
  38299. *
  38300. * @param {?('setup'|'analyze'|'generate')} buildStage - The build stage to set.
  38301. */
  38302. setBuildStage( buildStage ) {
  38303. this.buildStage = buildStage;
  38304. }
  38305. /**
  38306. * Returns the current build stage.
  38307. *
  38308. * @return {?('setup'|'analyze'|'generate')} The current build stage.
  38309. */
  38310. getBuildStage() {
  38311. return this.buildStage;
  38312. }
  38313. /**
  38314. * Controls the code build of the shader stages.
  38315. *
  38316. * @abstract
  38317. */
  38318. buildCode() {
  38319. warn( 'Abstract function.' );
  38320. }
  38321. /**
  38322. * Returns the current sub-build layer.
  38323. *
  38324. * @return {SubBuildNode} The current sub-build layers.
  38325. */
  38326. get subBuild() {
  38327. return this.subBuildLayers[ this.subBuildLayers.length - 1 ] || null;
  38328. }
  38329. /**
  38330. * Adds a sub-build layer to the node builder.
  38331. *
  38332. * @param {SubBuildNode} subBuild - The sub-build layer to add.
  38333. */
  38334. addSubBuild( subBuild ) {
  38335. this.subBuildLayers.push( subBuild );
  38336. }
  38337. /**
  38338. * Removes the last sub-build layer from the node builder.
  38339. *
  38340. * @return {SubBuildNode} The removed sub-build layer.
  38341. */
  38342. removeSubBuild() {
  38343. return this.subBuildLayers.pop();
  38344. }
  38345. /**
  38346. * Returns the closest sub-build layer for the given data.
  38347. *
  38348. * @param {Node|Set<string>|Array<string>} data - The data to get the closest sub-build layer from.
  38349. * @return {?string} The closest sub-build name or null if none found.
  38350. */
  38351. getClosestSubBuild( data ) {
  38352. let subBuilds;
  38353. if ( data && data.isNode ) {
  38354. if ( data.isShaderCallNodeInternal ) {
  38355. subBuilds = data.shaderNode.subBuilds;
  38356. } else if ( data.isStackNode ) {
  38357. subBuilds = [ data.subBuild ];
  38358. } else {
  38359. subBuilds = this.getDataFromNode( data, 'any' ).subBuilds;
  38360. }
  38361. } else if ( data instanceof Set ) {
  38362. subBuilds = [ ...data ];
  38363. } else {
  38364. subBuilds = data;
  38365. }
  38366. if ( ! subBuilds ) return null;
  38367. const subBuildLayers = this.subBuildLayers;
  38368. for ( let i = subBuilds.length - 1; i >= 0; i -- ) {
  38369. const subBuild = subBuilds[ i ];
  38370. if ( subBuildLayers.includes( subBuild ) ) {
  38371. return subBuild;
  38372. }
  38373. }
  38374. return null;
  38375. }
  38376. /**
  38377. * Returns the output node of a sub-build layer.
  38378. *
  38379. * @param {Node} node - The node to get the output from.
  38380. * @return {string} The output node name.
  38381. */
  38382. getSubBuildOutput( node ) {
  38383. return this.getSubBuildProperty( 'outputNode', node );
  38384. }
  38385. /**
  38386. * Returns the sub-build property name for the given property and node.
  38387. *
  38388. * @param {string} [property=''] - The property name.
  38389. * @param {?Node} [node=null] - The node to get the sub-build from.
  38390. * @return {string} The sub-build property name.
  38391. */
  38392. getSubBuildProperty( property = '', node = null ) {
  38393. let subBuild;
  38394. if ( node !== null ) {
  38395. subBuild = this.getClosestSubBuild( node );
  38396. } else {
  38397. subBuild = this.subBuildFn;
  38398. }
  38399. let result;
  38400. if ( subBuild ) {
  38401. result = property ? ( subBuild + '_' + property ) : subBuild;
  38402. } else {
  38403. result = property;
  38404. }
  38405. return result;
  38406. }
  38407. /**
  38408. * Prebuild the node builder.
  38409. */
  38410. prebuild() {
  38411. const { object, renderer, material } = this;
  38412. // < renderer.contextNode >
  38413. if ( renderer.contextNode.isContextNode === true ) {
  38414. this.context = { ...this.context, ...renderer.contextNode.getFlowContextData() };
  38415. } else {
  38416. error( 'NodeBuilder: "renderer.contextNode" must be an instance of `context()`.' );
  38417. }
  38418. // < material.contextNode >
  38419. if ( material && material.contextNode ) {
  38420. if ( material.contextNode.isContextNode === true ) {
  38421. this.context = { ...this.context, ...material.contextNode.getFlowContextData() };
  38422. } else {
  38423. error( 'NodeBuilder: "material.contextNode" must be an instance of `context()`.' );
  38424. }
  38425. }
  38426. // < nodeMaterial >
  38427. if ( material !== null ) {
  38428. let nodeMaterial = renderer.library.fromMaterial( material );
  38429. if ( nodeMaterial === null ) {
  38430. error( `NodeBuilder: Material "${ material.type }" is not compatible.` );
  38431. nodeMaterial = new NodeMaterial();
  38432. }
  38433. nodeMaterial.build( this );
  38434. } else {
  38435. this.addFlow( 'compute', object );
  38436. }
  38437. }
  38438. /**
  38439. * Central build method which controls the build for the given object.
  38440. *
  38441. * @return {NodeBuilder} A reference to this node builder.
  38442. */
  38443. build() {
  38444. this.prebuild();
  38445. // setup() -> stage 1: create possible new nodes and/or return an output reference node
  38446. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  38447. // generate() -> stage 3: generate shader
  38448. for ( const buildStage of defaultBuildStages ) {
  38449. this.setBuildStage( buildStage );
  38450. if ( this.context.position && this.context.position.isNode ) {
  38451. this.flowNodeFromShaderStage( 'vertex', this.context.position );
  38452. }
  38453. for ( const shaderStage of shaderStages ) {
  38454. this.setShaderStage( shaderStage );
  38455. const flowNodes = this.flowNodes[ shaderStage ];
  38456. for ( const node of flowNodes ) {
  38457. if ( buildStage === 'generate' ) {
  38458. this.flowNode( node );
  38459. } else {
  38460. node.build( this );
  38461. }
  38462. }
  38463. }
  38464. }
  38465. this.setBuildStage( null );
  38466. this.setShaderStage( null );
  38467. // stage 4: build code for a specific output
  38468. this.buildCode();
  38469. this.buildUpdateNodes();
  38470. return this;
  38471. }
  38472. /**
  38473. * Async version of build() that yields to main thread between shader stages.
  38474. * Use this in compileAsync() to prevent blocking the main thread.
  38475. *
  38476. * @return {Promise<NodeBuilder>} A promise that resolves to this node builder.
  38477. */
  38478. async buildAsync() {
  38479. this.prebuild();
  38480. // setup() -> stage 1: create possible new nodes and/or return an output reference node
  38481. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  38482. // generate() -> stage 3: generate shader
  38483. for ( const buildStage of defaultBuildStages ) {
  38484. this.setBuildStage( buildStage );
  38485. if ( this.context.position && this.context.position.isNode ) {
  38486. this.flowNodeFromShaderStage( 'vertex', this.context.position );
  38487. }
  38488. for ( const shaderStage of shaderStages ) {
  38489. this.setShaderStage( shaderStage );
  38490. const flowNodes = this.flowNodes[ shaderStage ];
  38491. for ( const node of flowNodes ) {
  38492. if ( buildStage === 'generate' ) {
  38493. this.flowNode( node );
  38494. } else {
  38495. node.build( this );
  38496. }
  38497. }
  38498. // Yield to main thread after each shader stage to prevent blocking
  38499. await yieldToMain();
  38500. }
  38501. }
  38502. this.setBuildStage( null );
  38503. this.setShaderStage( null );
  38504. // stage 4: build code for a specific output
  38505. this.buildCode();
  38506. this.buildUpdateNodes();
  38507. return this;
  38508. }
  38509. /**
  38510. * Returns shared data object for the given node.
  38511. *
  38512. * @param {Node} node - The node to get shared data from.
  38513. * @return {Object} The shared data.
  38514. */
  38515. getSharedDataFromNode( node ) {
  38516. let data = sharedNodeData.get( node );
  38517. if ( data === undefined ) {
  38518. data = {};
  38519. }
  38520. return data;
  38521. }
  38522. /**
  38523. * Returns a uniform representation which is later used for UBO generation and rendering.
  38524. *
  38525. * @param {NodeUniform} uniformNode - The uniform node.
  38526. * @param {string} type - The requested type.
  38527. * @return {Uniform} The uniform.
  38528. */
  38529. getNodeUniform( uniformNode, type ) {
  38530. const nodeData = this.getSharedDataFromNode( uniformNode );
  38531. let node = nodeData.cache;
  38532. if ( node === undefined ) {
  38533. if ( type === 'float' || type === 'int' || type === 'uint' ) node = new NumberNodeUniform( uniformNode );
  38534. else if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) node = new Vector2NodeUniform( uniformNode );
  38535. else if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) node = new Vector3NodeUniform( uniformNode );
  38536. else if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) node = new Vector4NodeUniform( uniformNode );
  38537. else if ( type === 'color' ) node = new ColorNodeUniform( uniformNode );
  38538. else if ( type === 'mat2' ) node = new Matrix2NodeUniform( uniformNode );
  38539. else if ( type === 'mat3' ) node = new Matrix3NodeUniform( uniformNode );
  38540. else if ( type === 'mat4' ) node = new Matrix4NodeUniform( uniformNode );
  38541. else {
  38542. throw new Error( `THREE.NodeBuilder: Uniform "${ type }" not implemented.` );
  38543. }
  38544. nodeData.cache = node;
  38545. }
  38546. return node;
  38547. }
  38548. /**
  38549. * Formats the given shader snippet from a given type into another one. E.g.
  38550. * this method might be used to convert a simple float string `"1.0"` into a
  38551. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  38552. *
  38553. * @param {string} snippet - The shader snippet.
  38554. * @param {string} fromType - The source type.
  38555. * @param {string} toType - The target type.
  38556. * @return {string} The updated shader string.
  38557. */
  38558. format( snippet, fromType, toType ) {
  38559. fromType = this.getVectorType( fromType );
  38560. toType = this.getVectorType( toType );
  38561. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  38562. return snippet;
  38563. }
  38564. const fromTypeLength = this.getTypeLength( fromType );
  38565. const toTypeLength = this.getTypeLength( toType );
  38566. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  38567. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xyz, ${ snippet }[ 1 ].xyz, ${ snippet }[ 2 ].xyz )`;
  38568. }
  38569. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  38570. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xy, ${ snippet }[ 1 ].xy )`;
  38571. }
  38572. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  38573. // @TODO: ignore for now
  38574. return snippet;
  38575. }
  38576. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  38577. // @TODO: ignore for now
  38578. return snippet;
  38579. }
  38580. if ( fromTypeLength === toTypeLength ) {
  38581. return `${ this.getType( toType ) }( ${ snippet } )`;
  38582. }
  38583. if ( fromTypeLength > toTypeLength ) {
  38584. snippet = toType === 'bool' ? `all( ${ snippet } )` : `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`;
  38585. return this.format( snippet, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  38586. }
  38587. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  38588. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  38589. }
  38590. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  38591. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  38592. }
  38593. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  38594. // convert a number value to vector type, e.g:
  38595. // vec3( 1u ) -> vec3( float( 1u ) )
  38596. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  38597. }
  38598. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  38599. }
  38600. /**
  38601. * Returns a signature with the engine's current revision.
  38602. *
  38603. * @return {string} The signature.
  38604. */
  38605. getSignature() {
  38606. return `// Three.js r${ REVISION } - Node System\n`;
  38607. }
  38608. /**
  38609. * Returns `true` if data from the previous frame are required. Relevant
  38610. * when computing motion vectors with {@link VelocityNode}.
  38611. *
  38612. * @return {boolean} Whether data from the previous frame are required or not.
  38613. */
  38614. needsPreviousData() {
  38615. const mrt = this.renderer.getMRT();
  38616. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( this.object ).useVelocity === true;
  38617. }
  38618. }
  38619. /**
  38620. * Management class for updating nodes. The module tracks metrics like
  38621. * the elapsed time, delta time, the render and frame ID to correctly
  38622. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  38623. * and {@link Node#updateAfter} depending on the node's configuration.
  38624. */
  38625. class NodeFrame {
  38626. /**
  38627. * Constructs a new node fame.
  38628. */
  38629. constructor() {
  38630. /**
  38631. * The elapsed time in seconds.
  38632. *
  38633. * @type {number}
  38634. * @default 0
  38635. */
  38636. this.time = 0;
  38637. /**
  38638. * The delta time in seconds.
  38639. *
  38640. * @type {number}
  38641. * @default 0
  38642. */
  38643. this.deltaTime = 0;
  38644. /**
  38645. * The frame ID.
  38646. *
  38647. * @type {number}
  38648. * @default 0
  38649. */
  38650. this.frameId = 0;
  38651. /**
  38652. * The render ID.
  38653. *
  38654. * @type {number}
  38655. * @default 0
  38656. */
  38657. this.renderId = 0;
  38658. /**
  38659. * Used to control the {@link Node#update} call.
  38660. *
  38661. * @type {WeakMap<Node, Object>}
  38662. */
  38663. this.updateMap = new WeakMap();
  38664. /**
  38665. * Used to control the {@link Node#updateBefore} call.
  38666. *
  38667. * @type {WeakMap<Node, Object>}
  38668. */
  38669. this.updateBeforeMap = new WeakMap();
  38670. /**
  38671. * Used to control the {@link Node#updateAfter} call.
  38672. *
  38673. * @type {WeakMap<Node, Object>}
  38674. */
  38675. this.updateAfterMap = new WeakMap();
  38676. /**
  38677. * A reference to the current renderer.
  38678. *
  38679. * @type {?Renderer}
  38680. * @default null
  38681. */
  38682. this.renderer = null;
  38683. /**
  38684. * A reference to the current material.
  38685. *
  38686. * @type {?Material}
  38687. * @default null
  38688. */
  38689. this.material = null;
  38690. /**
  38691. * A reference to the current camera.
  38692. *
  38693. * @type {?Camera}
  38694. * @default null
  38695. */
  38696. this.camera = null;
  38697. /**
  38698. * A reference to the current 3D object.
  38699. *
  38700. * @type {?Object3D}
  38701. * @default null
  38702. */
  38703. this.object = null;
  38704. /**
  38705. * A reference to the current scene.
  38706. *
  38707. * @type {?Scene}
  38708. * @default null
  38709. */
  38710. this.scene = null;
  38711. }
  38712. /**
  38713. * Returns a dictionary for a given node and update map which
  38714. * is used to correctly call node update methods per frame or render.
  38715. *
  38716. * @private
  38717. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  38718. * @param {Node} nodeRef - The reference to the current node.
  38719. * @return {Object<string,WeakMap<Object, number>>} The dictionary.
  38720. */
  38721. _getMaps( referenceMap, nodeRef ) {
  38722. let maps = referenceMap.get( nodeRef );
  38723. if ( maps === undefined ) {
  38724. maps = {
  38725. renderId: 0,
  38726. frameId: 0,
  38727. };
  38728. referenceMap.set( nodeRef, maps );
  38729. }
  38730. return maps;
  38731. }
  38732. /**
  38733. * This method executes the {@link Node#updateBefore} for the given node.
  38734. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  38735. * is only executed once per frame, render or object depending on the update
  38736. * type.
  38737. *
  38738. * @param {Node} node - The node that should be updated.
  38739. */
  38740. updateBeforeNode( node ) {
  38741. const updateType = node.getUpdateBeforeType();
  38742. const reference = node.updateReference( this );
  38743. if ( updateType === NodeUpdateType.FRAME ) {
  38744. const nodeUpdateBeforeMap = this._getMaps( this.updateBeforeMap, reference );
  38745. if ( nodeUpdateBeforeMap.frameId !== this.frameId ) {
  38746. const previousFrameId = nodeUpdateBeforeMap.frameId;
  38747. nodeUpdateBeforeMap.frameId = this.frameId;
  38748. if ( node.updateBefore( this ) === false ) {
  38749. nodeUpdateBeforeMap.frameId = previousFrameId;
  38750. }
  38751. }
  38752. } else if ( updateType === NodeUpdateType.RENDER ) {
  38753. const nodeUpdateBeforeMap = this._getMaps( this.updateBeforeMap, reference );
  38754. if ( nodeUpdateBeforeMap.renderId !== this.renderId ) {
  38755. const previousRenderId = nodeUpdateBeforeMap.renderId;
  38756. nodeUpdateBeforeMap.renderId = this.renderId;
  38757. if ( node.updateBefore( this ) === false ) {
  38758. nodeUpdateBeforeMap.renderId = previousRenderId;
  38759. }
  38760. }
  38761. } else if ( updateType === NodeUpdateType.OBJECT ) {
  38762. node.updateBefore( this );
  38763. }
  38764. }
  38765. /**
  38766. * This method executes the {@link Node#updateAfter} for the given node.
  38767. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  38768. * is only executed once per frame, render or object depending on the update
  38769. * type.
  38770. *
  38771. * @param {Node} node - The node that should be updated.
  38772. */
  38773. updateAfterNode( node ) {
  38774. const updateType = node.getUpdateAfterType();
  38775. const reference = node.updateReference( this );
  38776. if ( updateType === NodeUpdateType.FRAME ) {
  38777. const nodeUpdateAfterMap = this._getMaps( this.updateAfterMap, reference );
  38778. if ( nodeUpdateAfterMap.frameId !== this.frameId ) {
  38779. if ( node.updateAfter( this ) !== false ) {
  38780. nodeUpdateAfterMap.frameId = this.frameId;
  38781. }
  38782. }
  38783. } else if ( updateType === NodeUpdateType.RENDER ) {
  38784. const nodeUpdateAfterMap = this._getMaps( this.updateAfterMap, reference );
  38785. if ( nodeUpdateAfterMap.renderId !== this.renderId ) {
  38786. if ( node.updateAfter( this ) !== false ) {
  38787. nodeUpdateAfterMap.renderId = this.renderId;
  38788. }
  38789. }
  38790. } else if ( updateType === NodeUpdateType.OBJECT ) {
  38791. node.updateAfter( this );
  38792. }
  38793. }
  38794. /**
  38795. * This method executes the {@link Node#update} for the given node.
  38796. * It makes sure {@link Node#updateType} is honored meaning the update
  38797. * is only executed once per frame, render or object depending on the update
  38798. * type.
  38799. *
  38800. * @param {Node} node - The node that should be updated.
  38801. */
  38802. updateNode( node ) {
  38803. const updateType = node.getUpdateType();
  38804. const reference = node.updateReference( this );
  38805. if ( updateType === NodeUpdateType.FRAME ) {
  38806. const nodeUpdateMap = this._getMaps( this.updateMap, reference );
  38807. if ( nodeUpdateMap.frameId !== this.frameId ) {
  38808. if ( node.update( this ) !== false ) {
  38809. nodeUpdateMap.frameId = this.frameId;
  38810. }
  38811. }
  38812. } else if ( updateType === NodeUpdateType.RENDER ) {
  38813. const nodeUpdateMap = this._getMaps( this.updateMap, reference );
  38814. if ( nodeUpdateMap.renderId !== this.renderId ) {
  38815. if ( node.update( this ) !== false ) {
  38816. nodeUpdateMap.renderId = this.renderId;
  38817. }
  38818. }
  38819. } else if ( updateType === NodeUpdateType.OBJECT ) {
  38820. node.update( this );
  38821. }
  38822. }
  38823. /**
  38824. * Updates the internal state of the node frame. This method is
  38825. * called by the renderer in its internal animation loop.
  38826. */
  38827. update() {
  38828. this.frameId ++;
  38829. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  38830. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  38831. this.lastTime = performance.now();
  38832. this.time += this.deltaTime;
  38833. }
  38834. }
  38835. /**
  38836. * Describes the input of a {@link NodeFunction}.
  38837. */
  38838. class NodeFunctionInput {
  38839. /**
  38840. * Constructs a new node function input.
  38841. *
  38842. * @param {string} type - The input type.
  38843. * @param {string} name - The input name.
  38844. * @param {?number} [count=null] - If the input is an Array, count will be the length.
  38845. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  38846. * @param {boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  38847. */
  38848. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  38849. /**
  38850. * The input type.
  38851. *
  38852. * @type {string}
  38853. */
  38854. this.type = type;
  38855. /**
  38856. * The input name.
  38857. *
  38858. * @type {string}
  38859. */
  38860. this.name = name;
  38861. /**
  38862. * If the input is an Array, count will be the length.
  38863. *
  38864. * @type {?number}
  38865. * @default null
  38866. */
  38867. this.count = count;
  38868. /**
  38869. *The parameter qualifier (only relevant for GLSL).
  38870. *
  38871. * @type {('in'|'out'|'inout')}
  38872. * @default ''
  38873. */
  38874. this.qualifier = qualifier;
  38875. /**
  38876. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  38877. *
  38878. * @type {boolean}
  38879. * @default false
  38880. */
  38881. this.isConst = isConst;
  38882. }
  38883. }
  38884. NodeFunctionInput.isNodeFunctionInput = true;
  38885. /**
  38886. * Module for representing ambient lights as nodes.
  38887. *
  38888. * @augments AnalyticLightNode
  38889. */
  38890. class AmbientLightNode extends AnalyticLightNode {
  38891. static get type() {
  38892. return 'AmbientLightNode';
  38893. }
  38894. /**
  38895. * Constructs a new ambient light node.
  38896. *
  38897. * @param {?AmbientLight} [light=null] - The ambient light source.
  38898. */
  38899. constructor( light = null ) {
  38900. super( light );
  38901. }
  38902. setup( { context } ) {
  38903. context.irradiance.addAssign( this.colorNode );
  38904. }
  38905. }
  38906. /**
  38907. * Module for representing directional lights as nodes.
  38908. *
  38909. * @augments AnalyticLightNode
  38910. */
  38911. class DirectionalLightNode extends AnalyticLightNode {
  38912. static get type() {
  38913. return 'DirectionalLightNode';
  38914. }
  38915. /**
  38916. * Constructs a new directional light node.
  38917. *
  38918. * @param {?DirectionalLight} [light=null] - The directional light source.
  38919. */
  38920. constructor( light = null ) {
  38921. super( light );
  38922. }
  38923. setupDirect() {
  38924. const lightColor = this.colorNode;
  38925. const lightDirection = lightTargetDirection( this.light );
  38926. return { lightDirection, lightColor };
  38927. }
  38928. }
  38929. /**
  38930. * Module for representing hemisphere lights as nodes.
  38931. *
  38932. * @augments AnalyticLightNode
  38933. */
  38934. class HemisphereLightNode extends AnalyticLightNode {
  38935. static get type() {
  38936. return 'HemisphereLightNode';
  38937. }
  38938. /**
  38939. * Constructs a new hemisphere light node.
  38940. *
  38941. * @param {?HemisphereLight} [light=null] - The hemisphere light source.
  38942. */
  38943. constructor( light = null ) {
  38944. super( light );
  38945. /**
  38946. * Uniform node representing the light's position.
  38947. *
  38948. * @type {UniformNode<vec3>}
  38949. */
  38950. this.lightPositionNode = lightPosition( light );
  38951. /**
  38952. * A node representing the light's direction.
  38953. *
  38954. * @type {Node<vec3>}
  38955. */
  38956. this.lightDirectionNode = this.lightPositionNode.normalize();
  38957. /**
  38958. * Uniform node representing the light's ground color.
  38959. *
  38960. * @type {UniformNode<vec3>}
  38961. */
  38962. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  38963. }
  38964. /**
  38965. * Overwritten to updated hemisphere light specific uniforms.
  38966. *
  38967. * @param {NodeFrame} frame - A reference to the current node frame.
  38968. */
  38969. update( frame ) {
  38970. const { light } = this;
  38971. super.update( frame );
  38972. this.lightPositionNode.object3d = light;
  38973. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  38974. }
  38975. setup( builder ) {
  38976. const { colorNode, groundColorNode, lightDirectionNode } = this;
  38977. const dotNL = normalWorld.dot( lightDirectionNode );
  38978. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  38979. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  38980. builder.context.irradiance.addAssign( irradiance );
  38981. }
  38982. }
  38983. /**
  38984. * Module for representing spot lights as nodes.
  38985. *
  38986. * @augments AnalyticLightNode
  38987. */
  38988. class SpotLightNode extends AnalyticLightNode {
  38989. static get type() {
  38990. return 'SpotLightNode';
  38991. }
  38992. /**
  38993. * Constructs a new spot light node.
  38994. *
  38995. * @param {?SpotLight} [light=null] - The spot light source.
  38996. */
  38997. constructor( light = null ) {
  38998. super( light );
  38999. /**
  39000. * Uniform node representing the cone cosine.
  39001. *
  39002. * @type {UniformNode<float>}
  39003. */
  39004. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  39005. /**
  39006. * Uniform node representing the penumbra cosine.
  39007. *
  39008. * @type {UniformNode<float>}
  39009. */
  39010. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  39011. /**
  39012. * Uniform node representing the cutoff distance.
  39013. *
  39014. * @type {UniformNode<float>}
  39015. */
  39016. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  39017. /**
  39018. * Uniform node representing the decay exponent.
  39019. *
  39020. * @type {UniformNode<float>}
  39021. */
  39022. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  39023. /**
  39024. * Uniform node representing the light color.
  39025. *
  39026. * @type {UniformNode<Color>}
  39027. */
  39028. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  39029. }
  39030. /**
  39031. * Overwritten to updated spot light specific uniforms.
  39032. *
  39033. * @param {NodeFrame} frame - A reference to the current node frame.
  39034. */
  39035. update( frame ) {
  39036. super.update( frame );
  39037. const { light } = this;
  39038. this.coneCosNode.value = Math.cos( light.angle );
  39039. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  39040. this.cutoffDistanceNode.value = light.distance;
  39041. this.decayExponentNode.value = light.decay;
  39042. }
  39043. /**
  39044. * Computes the spot attenuation for the given angle.
  39045. *
  39046. * @param {NodeBuilder} builder - The node builder.
  39047. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  39048. * @return {Node<float>} The spot attenuation.
  39049. */
  39050. getSpotAttenuation( builder, angleCosine ) {
  39051. const { coneCosNode, penumbraCosNode } = this;
  39052. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  39053. }
  39054. getLightCoord( builder ) {
  39055. const properties = builder.getNodeProperties( this );
  39056. let projectionUV = properties.projectionUV;
  39057. if ( projectionUV === undefined ) {
  39058. projectionUV = lightProjectionUV( this.light, builder.context.positionWorld );
  39059. properties.projectionUV = projectionUV;
  39060. }
  39061. return projectionUV;
  39062. }
  39063. setupDirect( builder ) {
  39064. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  39065. const lightVector = this.getLightVector( builder );
  39066. const lightDirection = lightVector.normalize();
  39067. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  39068. const spotAttenuation = this.getSpotAttenuation( builder, angleCos );
  39069. const lightDistance = lightVector.length();
  39070. const lightAttenuation = getDistanceAttenuation( {
  39071. lightDistance,
  39072. cutoffDistance: cutoffDistanceNode,
  39073. decayExponent: decayExponentNode
  39074. } );
  39075. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  39076. let projected, lightCoord;
  39077. if ( light.colorNode ) {
  39078. lightCoord = this.getLightCoord( builder );
  39079. projected = light.colorNode( lightCoord );
  39080. } else if ( light.map ) {
  39081. lightCoord = this.getLightCoord( builder );
  39082. projected = texture( light.map, lightCoord.xy ).onRenderUpdate( () => light.map );
  39083. }
  39084. if ( projected ) {
  39085. const inSpotLightMap = lightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  39086. lightColor = inSpotLightMap.select( lightColor.mul( projected ), lightColor );
  39087. }
  39088. return { lightColor, lightDirection };
  39089. }
  39090. }
  39091. /**
  39092. * An IES version of the default spot light node.
  39093. *
  39094. * @augments SpotLightNode
  39095. */
  39096. class IESSpotLightNode extends SpotLightNode {
  39097. static get type() {
  39098. return 'IESSpotLightNode';
  39099. }
  39100. /**
  39101. * Constructs a new IES spot light node.
  39102. *
  39103. * @param {?SpotLight} [light=null] - The spot light source.
  39104. */
  39105. constructor( light = null ) {
  39106. super( light );
  39107. /**
  39108. * The texture node representing the IES texture.
  39109. *
  39110. * @type {?TextureNode}
  39111. * @default null
  39112. */
  39113. this._iesTextureNode = null;
  39114. }
  39115. /**
  39116. * Overwrites the default implementation to compute an IES conform spot attenuation.
  39117. *
  39118. * @param {NodeBuilder} builder - The node builder.
  39119. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  39120. * @return {Node<float>} The spot attenuation.
  39121. */
  39122. getSpotAttenuation( builder, angleCosine ) {
  39123. const iesMap = this.light.iesMap;
  39124. let spotAttenuation = null;
  39125. if ( iesMap && iesMap.isTexture === true ) {
  39126. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  39127. this._iesTextureNode = texture( iesMap, vec2( angle, 0 ), 0 );
  39128. spotAttenuation = this._iesTextureNode.r;
  39129. } else {
  39130. spotAttenuation = super.getSpotAttenuation( builder, angleCosine );
  39131. }
  39132. return spotAttenuation;
  39133. }
  39134. /**
  39135. * Overwritten to update the IES spot light texture.
  39136. *
  39137. * @param {NodeFrame} frame - A reference to the current node frame.
  39138. */
  39139. update( frame ) {
  39140. super.update( frame );
  39141. if ( this._iesTextureNode !== null && this.light.iesMap ) {
  39142. this._iesTextureNode.value = this.light.iesMap;
  39143. }
  39144. }
  39145. }
  39146. /**
  39147. * Module for representing light probes as nodes.
  39148. *
  39149. * @augments AnalyticLightNode
  39150. */
  39151. class LightProbeNode extends AnalyticLightNode {
  39152. static get type() {
  39153. return 'LightProbeNode';
  39154. }
  39155. /**
  39156. * Constructs a new light probe node.
  39157. *
  39158. * @param {?LightProbe} [light=null] - The light probe.
  39159. */
  39160. constructor( light = null ) {
  39161. super( light );
  39162. const array = [];
  39163. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  39164. /**
  39165. * Light probe represented as a uniform of spherical harmonics.
  39166. *
  39167. * @type {UniformArrayNode}
  39168. */
  39169. this.lightProbe = uniformArray( array );
  39170. }
  39171. /**
  39172. * Overwritten to updated light probe specific uniforms.
  39173. *
  39174. * @param {NodeFrame} frame - A reference to the current node frame.
  39175. */
  39176. update( frame ) {
  39177. const { light } = this;
  39178. super.update( frame );
  39179. //
  39180. for ( let i = 0; i < 9; i ++ ) {
  39181. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  39182. }
  39183. }
  39184. setup( builder ) {
  39185. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  39186. builder.context.irradiance.addAssign( irradiance );
  39187. }
  39188. }
  39189. const sdBox = /*@__PURE__*/ Fn( ( [ p, b ] ) => {
  39190. const d = p.abs().sub( b );
  39191. return length( max$1( d, 0.0 ) ).add( min$1( max$1( d.x, d.y ), 0.0 ) );
  39192. } );
  39193. /**
  39194. * An implementation of a projector light node.
  39195. *
  39196. * @augments SpotLightNode
  39197. */
  39198. class ProjectorLightNode extends SpotLightNode {
  39199. static get type() {
  39200. return 'ProjectorLightNode';
  39201. }
  39202. update( frame ) {
  39203. super.update( frame );
  39204. const light = this.light;
  39205. this.penumbraCosNode.value = Math.min( Math.cos( light.angle * ( 1 - light.penumbra ) ), .99999 );
  39206. if ( light.aspect === null ) {
  39207. let aspect = 1;
  39208. if ( light.map !== null ) {
  39209. aspect = light.map.width / light.map.height;
  39210. }
  39211. light.shadow.aspect = aspect;
  39212. } else {
  39213. light.shadow.aspect = light.aspect;
  39214. }
  39215. }
  39216. /**
  39217. * Overwrites the default implementation to compute projection attenuation.
  39218. *
  39219. * @param {NodeBuilder} builder - The node builder.
  39220. * @return {Node<float>} The spot attenuation.
  39221. */
  39222. getSpotAttenuation( builder ) {
  39223. const attenuation = float( 0 );
  39224. const penumbraCos = this.penumbraCosNode;
  39225. // compute the fragment's position in the light's clip space
  39226. const spotLightCoord = lightShadowMatrix( this.light ).mul( builder.context.positionWorld || positionWorld );
  39227. // the sign of w determines whether the current fragment is in front or behind the light.
  39228. // to avoid a back-projection, it's important to only compute an attenuation if w is positive
  39229. If( spotLightCoord.w.greaterThan( 0 ), () => {
  39230. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  39231. const boxDist = sdBox( projectionUV.xy.sub( vec2( 0.5 ) ), vec2( 0.5 ) );
  39232. const angleFactor = div( -1, sub( 1.0, acos( penumbraCos ) ).sub( 1.0 ) );
  39233. attenuation.assign( saturate( boxDist.mul( -2 ).mul( angleFactor ) ) );
  39234. } );
  39235. return attenuation;
  39236. }
  39237. }
  39238. const _matrix41 = /*@__PURE__*/ new Matrix4();
  39239. const _matrix42 = /*@__PURE__*/ new Matrix4();
  39240. let _ltcLib = null;
  39241. /**
  39242. * Module for representing rect area lights as nodes.
  39243. *
  39244. * @augments AnalyticLightNode
  39245. */
  39246. class RectAreaLightNode extends AnalyticLightNode {
  39247. static get type() {
  39248. return 'RectAreaLightNode';
  39249. }
  39250. /**
  39251. * Constructs a new rect area light node.
  39252. *
  39253. * @param {?RectAreaLight} [light=null] - The rect area light source.
  39254. */
  39255. constructor( light = null ) {
  39256. super( light );
  39257. /**
  39258. * Uniform node representing the half height of the are light.
  39259. *
  39260. * @type {UniformNode<vec3>}
  39261. */
  39262. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  39263. /**
  39264. * Uniform node representing the half width of the are light.
  39265. *
  39266. * @type {UniformNode<vec3>}
  39267. */
  39268. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  39269. /**
  39270. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  39271. * relies on `viewMatrix` which might vary per render call.
  39272. *
  39273. * @type {string}
  39274. * @default 'render'
  39275. */
  39276. this.updateType = NodeUpdateType.RENDER;
  39277. }
  39278. /**
  39279. * Overwritten to updated rect area light specific uniforms.
  39280. *
  39281. * @param {NodeFrame} frame - A reference to the current node frame.
  39282. */
  39283. update( frame ) {
  39284. super.update( frame );
  39285. const { light } = this;
  39286. const viewMatrix = frame.camera.matrixWorldInverse;
  39287. _matrix42.identity();
  39288. _matrix41.copy( light.matrixWorld );
  39289. _matrix41.premultiply( viewMatrix );
  39290. _matrix42.extractRotation( _matrix41 );
  39291. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  39292. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  39293. this.halfWidth.value.applyMatrix4( _matrix42 );
  39294. this.halfHeight.value.applyMatrix4( _matrix42 );
  39295. }
  39296. setupDirectRectArea( builder ) {
  39297. let ltc_1, ltc_2;
  39298. if ( builder.isAvailable( 'float32Filterable' ) ) {
  39299. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  39300. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  39301. } else {
  39302. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  39303. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  39304. }
  39305. const { colorNode, light } = this;
  39306. const lightPosition = lightViewPosition( light );
  39307. return {
  39308. lightColor: colorNode,
  39309. lightPosition,
  39310. halfWidth: this.halfWidth,
  39311. halfHeight: this.halfHeight,
  39312. ltc_1,
  39313. ltc_2
  39314. };
  39315. }
  39316. /**
  39317. * Used to configure the internal BRDF approximation texture data.
  39318. *
  39319. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  39320. */
  39321. static setLTC( ltc ) {
  39322. _ltcLib = ltc;
  39323. }
  39324. }
  39325. /**
  39326. * Base class for node parsers. A derived parser must be implemented
  39327. * for each supported native shader language.
  39328. */
  39329. class NodeParser {
  39330. /**
  39331. * The method parses the given native code an returns a node function.
  39332. *
  39333. * @abstract
  39334. * @param {string} source - The native shader code.
  39335. * @return {NodeFunction} A node function.
  39336. */
  39337. parseFunction( /*source*/ ) {
  39338. warn( 'Abstract function.' );
  39339. }
  39340. }
  39341. /**
  39342. * Base class for node functions. A derived module must be implemented
  39343. * for each supported native shader language. Similar to other `Node*` modules,
  39344. * this class is only relevant during the building process and not used
  39345. * in user-level code.
  39346. */
  39347. class NodeFunction {
  39348. /**
  39349. * Constructs a new node function.
  39350. *
  39351. * @param {string} type - The node type. This type is the return type of the node function.
  39352. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  39353. * @param {string} [name=''] - The function's name.
  39354. * @param {string} [precision=''] - The precision qualifier.
  39355. */
  39356. constructor( type, inputs, name = '', precision = '' ) {
  39357. /**
  39358. * The node type. This type is the return type of the node function.
  39359. *
  39360. * @type {string}
  39361. */
  39362. this.type = type;
  39363. /**
  39364. * The function's inputs.
  39365. *
  39366. * @type {Array<NodeFunctionInput>}
  39367. */
  39368. this.inputs = inputs;
  39369. /**
  39370. * The name of the uniform.
  39371. *
  39372. * @type {string}
  39373. * @default ''
  39374. */
  39375. this.name = name;
  39376. /**
  39377. * The precision qualifier.
  39378. *
  39379. * @type {string}
  39380. * @default ''
  39381. */
  39382. this.precision = precision;
  39383. }
  39384. /**
  39385. * This method returns the native code of the node function.
  39386. *
  39387. * @abstract
  39388. * @param {string} name - The function's name.
  39389. * @return {string} A shader code.
  39390. */
  39391. getCode( /*name = this.name*/ ) {
  39392. warn( 'Abstract function.' );
  39393. }
  39394. }
  39395. NodeFunction.isNodeFunction = true;
  39396. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  39397. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  39398. const pragmaMain = '#pragma main';
  39399. const parse$1 = ( source ) => {
  39400. source = source.trim();
  39401. const pragmaMainIndex = source.indexOf( pragmaMain );
  39402. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  39403. const declaration = mainCode.match( declarationRegexp$1 );
  39404. if ( declaration !== null && declaration.length === 5 ) {
  39405. // tokenizer
  39406. const inputsCode = declaration[ 4 ];
  39407. const propsMatches = [];
  39408. let nameMatch = null;
  39409. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  39410. propsMatches.push( nameMatch );
  39411. }
  39412. // parser
  39413. const inputs = [];
  39414. let i = 0;
  39415. while ( i < propsMatches.length ) {
  39416. const isConst = propsMatches[ i ][ 0 ] === 'const';
  39417. if ( isConst === true ) {
  39418. i ++;
  39419. }
  39420. let qualifier = propsMatches[ i ][ 0 ];
  39421. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  39422. i ++;
  39423. } else {
  39424. qualifier = '';
  39425. }
  39426. const type = propsMatches[ i ++ ][ 0 ];
  39427. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  39428. if ( Number.isNaN( count ) === false ) i ++;
  39429. else count = null;
  39430. const name = propsMatches[ i ++ ][ 0 ];
  39431. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  39432. }
  39433. //
  39434. const blockCode = mainCode.substring( declaration[ 0 ].length );
  39435. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  39436. const type = declaration[ 2 ];
  39437. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  39438. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  39439. return {
  39440. type,
  39441. inputs,
  39442. name,
  39443. precision,
  39444. inputsCode,
  39445. blockCode,
  39446. headerCode
  39447. };
  39448. } else {
  39449. throw new Error( 'THREE.FunctionNode: Function is not a GLSL code.' );
  39450. }
  39451. };
  39452. /**
  39453. * This class represents a GLSL node function.
  39454. *
  39455. * @augments NodeFunction
  39456. */
  39457. class GLSLNodeFunction extends NodeFunction {
  39458. /**
  39459. * Constructs a new GLSL node function.
  39460. *
  39461. * @param {string} source - The GLSL source.
  39462. */
  39463. constructor( source ) {
  39464. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  39465. super( type, inputs, name, precision );
  39466. this.inputsCode = inputsCode;
  39467. this.blockCode = blockCode;
  39468. this.headerCode = headerCode;
  39469. }
  39470. /**
  39471. * This method returns the GLSL code of the node function.
  39472. *
  39473. * @param {string} [name=this.name] - The function's name.
  39474. * @return {string} The shader code.
  39475. */
  39476. getCode( name = this.name ) {
  39477. let code;
  39478. const blockCode = this.blockCode;
  39479. if ( blockCode !== '' ) {
  39480. const { type, inputsCode, headerCode, precision } = this;
  39481. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  39482. if ( precision !== '' ) {
  39483. declarationCode = `${ precision } ${ declarationCode }`;
  39484. }
  39485. code = headerCode + declarationCode + blockCode;
  39486. } else {
  39487. // interface function
  39488. code = '';
  39489. }
  39490. return code;
  39491. }
  39492. }
  39493. /**
  39494. * A GLSL node parser.
  39495. *
  39496. * @augments NodeParser
  39497. */
  39498. class GLSLNodeParser extends NodeParser {
  39499. /**
  39500. * The method parses the given GLSL code an returns a node function.
  39501. *
  39502. * @param {string} source - The GLSL code.
  39503. * @return {GLSLNodeFunction} A node function.
  39504. */
  39505. parseFunction( source ) {
  39506. return new GLSLNodeFunction( source );
  39507. }
  39508. }
  39509. const _chainKeys$1 = [];
  39510. const _cacheKeyValues = [];
  39511. // Dedicated uniform for output pass array layer selection
  39512. // This is separate from cameraIndex to avoid the sharedUniformGroup complexity
  39513. const _outputLayerIndex = /*@__PURE__*/ uniform( 0, 'int' ).setGroup( renderGroup );
  39514. /**
  39515. * This renderer module manages node-related objects and is the
  39516. * primary interface between the renderer and the node system.
  39517. *
  39518. * @private
  39519. * @augments DataMap
  39520. */
  39521. class NodeManager extends DataMap {
  39522. /**
  39523. * Constructs a new nodes management component.
  39524. *
  39525. * @param {Renderer} renderer - The renderer.
  39526. * @param {Backend} backend - The renderer's backend.
  39527. */
  39528. constructor( renderer, backend ) {
  39529. super();
  39530. /**
  39531. * The renderer.
  39532. *
  39533. * @type {Renderer}
  39534. */
  39535. this.renderer = renderer;
  39536. /**
  39537. * The renderer's backend.
  39538. *
  39539. * @type {Backend}
  39540. */
  39541. this.backend = backend;
  39542. /**
  39543. * The node frame.
  39544. *
  39545. * @type {Renderer}
  39546. */
  39547. this.nodeFrame = new NodeFrame();
  39548. /**
  39549. * A cache for managing node builder states.
  39550. *
  39551. * @type {Map<number,NodeBuilderState>}
  39552. */
  39553. this.nodeBuilderCache = new Map();
  39554. /**
  39555. * A cache for managing data cache key data.
  39556. *
  39557. * @type {ChainMap}
  39558. */
  39559. this.callHashCache = new ChainMap();
  39560. /**
  39561. * A cache for managing node uniforms group data.
  39562. *
  39563. * @type {ChainMap}
  39564. */
  39565. this.groupsData = new ChainMap();
  39566. /**
  39567. * Queue for pending async builds to limit concurrent compilation.
  39568. *
  39569. * @private
  39570. * @type {Array<Function>}
  39571. */
  39572. this._buildQueue = [];
  39573. /**
  39574. * Whether an async build is currently in progress.
  39575. *
  39576. * @private
  39577. * @type {boolean}
  39578. */
  39579. this._buildInProgress = false;
  39580. /**
  39581. * A cache for managing node objects of
  39582. * scene properties like fog or environments.
  39583. *
  39584. * @type {Object<string,WeakMap>}
  39585. */
  39586. this.cacheLib = {};
  39587. }
  39588. /**
  39589. * Returns `true` if the given node uniforms group must be updated or not.
  39590. *
  39591. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  39592. * @return {boolean} Whether the node uniforms group requires an update or not.
  39593. */
  39594. updateGroup( nodeUniformsGroup ) {
  39595. const groupNode = nodeUniformsGroup.groupNode;
  39596. // groups that are updated per object always require an update so no further checks are needed
  39597. if ( groupNode.updateType === NodeUpdateType.OBJECT ) return true;
  39598. // check for update
  39599. _chainKeys$1[ 0 ] = groupNode;
  39600. _chainKeys$1[ 1 ] = nodeUniformsGroup;
  39601. let groupData = this.groupsData.get( _chainKeys$1 );
  39602. if ( groupData === undefined ) this.groupsData.set( _chainKeys$1, groupData = {} );
  39603. _chainKeys$1[ 0 ] = null;
  39604. _chainKeys$1[ 1 ] = null;
  39605. if ( groupData.version !== groupNode.version ) {
  39606. groupData.version = groupNode.version;
  39607. return true;
  39608. }
  39609. return false;
  39610. }
  39611. /**
  39612. * Returns the cache key for the given render object.
  39613. *
  39614. * @param {RenderObject} renderObject - The render object.
  39615. * @return {number} The cache key.
  39616. */
  39617. getForRenderCacheKey( renderObject ) {
  39618. return renderObject.initialCacheKey;
  39619. }
  39620. /**
  39621. * Creates a node builder configured for the given render object and material.
  39622. *
  39623. * @private
  39624. * @param {RenderObject} renderObject - The render object.
  39625. * @param {Material} material - The material to use.
  39626. * @return {NodeBuilder} The configured node builder.
  39627. */
  39628. _createNodeBuilder( renderObject, material ) {
  39629. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  39630. nodeBuilder.scene = renderObject.scene;
  39631. nodeBuilder.material = material;
  39632. nodeBuilder.camera = renderObject.camera;
  39633. nodeBuilder.context.material = material;
  39634. nodeBuilder.lightsNode = renderObject.lightsNode;
  39635. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  39636. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  39637. nodeBuilder.clippingContext = renderObject.clippingContext;
  39638. if ( this.renderer.getOutputRenderTarget() ? this.renderer.getOutputRenderTarget().multiview : false ) {
  39639. nodeBuilder.enableMultiview();
  39640. }
  39641. return nodeBuilder;
  39642. }
  39643. /**
  39644. * Returns a node builder state for the given render object.
  39645. *
  39646. * @param {RenderObject} renderObject - The render object.
  39647. * @param {boolean} [useAsync=false] - Whether to use async build with yielding.
  39648. * @return {NodeBuilderState|Promise<NodeBuilderState>} The node builder state (or Promise if async).
  39649. */
  39650. getForRender( renderObject, useAsync = false ) {
  39651. const renderObjectData = this.get( renderObject );
  39652. let nodeBuilderState = renderObjectData.nodeBuilderState;
  39653. if ( nodeBuilderState === undefined ) {
  39654. const { nodeBuilderCache } = this;
  39655. const cacheKey = this.getForRenderCacheKey( renderObject );
  39656. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  39657. if ( nodeBuilderState === undefined ) {
  39658. const buildNodeBuilder = async () => {
  39659. let nodeBuilder = this._createNodeBuilder( renderObject, renderObject.material );
  39660. try {
  39661. if ( useAsync ) {
  39662. await nodeBuilder.buildAsync();
  39663. } else {
  39664. nodeBuilder.build();
  39665. }
  39666. } catch ( e ) {
  39667. nodeBuilder = this._createNodeBuilder( renderObject, new NodeMaterial() );
  39668. if ( useAsync ) {
  39669. await nodeBuilder.buildAsync();
  39670. } else {
  39671. nodeBuilder.build();
  39672. }
  39673. error( 'TSL: ' + e );
  39674. }
  39675. return nodeBuilder;
  39676. };
  39677. if ( useAsync ) {
  39678. return buildNodeBuilder().then( ( nodeBuilder ) => {
  39679. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  39680. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  39681. nodeBuilderState.usedTimes ++;
  39682. renderObjectData.nodeBuilderState = nodeBuilderState;
  39683. return nodeBuilderState;
  39684. } );
  39685. } else {
  39686. // Synchronous path - call buildNodeBuilder but don't await
  39687. let nodeBuilder = this._createNodeBuilder( renderObject, renderObject.material );
  39688. try {
  39689. nodeBuilder.build();
  39690. } catch ( e ) {
  39691. nodeBuilder = this._createNodeBuilder( renderObject, new NodeMaterial() );
  39692. nodeBuilder.build();
  39693. let stackTrace = e.stackTrace;
  39694. if ( ! stackTrace && e.stack ) {
  39695. // Capture stack trace for JavaScript errors
  39696. stackTrace = new StackTrace( e.stack );
  39697. }
  39698. error( 'TSL: ' + e, stackTrace );
  39699. }
  39700. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  39701. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  39702. }
  39703. }
  39704. nodeBuilderState.usedTimes ++;
  39705. renderObjectData.nodeBuilderState = nodeBuilderState;
  39706. }
  39707. return nodeBuilderState;
  39708. }
  39709. /**
  39710. * Async version of getForRender() that yields to main thread during build.
  39711. * Use this in compileAsync() to prevent blocking the main thread.
  39712. *
  39713. * @param {RenderObject} renderObject - The render object.
  39714. * @return {Promise<NodeBuilderState>} A promise that resolves to the node builder state.
  39715. */
  39716. getForRenderAsync( renderObject ) {
  39717. const result = this.getForRender( renderObject, true );
  39718. // Ensure we always return a Promise (cache hit returns nodeBuilderState directly)
  39719. if ( result.then ) {
  39720. return result;
  39721. }
  39722. return Promise.resolve( result );
  39723. }
  39724. /**
  39725. * Returns nodeBuilderState if ready, null if pending async build.
  39726. * Queues async build on first call for cache miss.
  39727. * Use this in render() path to enable non-blocking compilation.
  39728. *
  39729. * @param {RenderObject} renderObject - The render object.
  39730. * @return {?NodeBuilderState} The node builder state, or null if still building.
  39731. */
  39732. getForRenderDeferred( renderObject ) {
  39733. const renderObjectData = this.get( renderObject );
  39734. // Already built for this renderObject
  39735. if ( renderObjectData.nodeBuilderState !== undefined ) {
  39736. return renderObjectData.nodeBuilderState;
  39737. }
  39738. // Check cache with stable key
  39739. const cacheKey = this.getForRenderCacheKey( renderObject );
  39740. const nodeBuilderState = this.nodeBuilderCache.get( cacheKey );
  39741. if ( nodeBuilderState !== undefined ) {
  39742. // Cache hit - use it
  39743. nodeBuilderState.usedTimes ++;
  39744. renderObjectData.nodeBuilderState = nodeBuilderState;
  39745. return nodeBuilderState;
  39746. }
  39747. // Cache miss - check if async build already queued
  39748. if ( renderObjectData.pendingBuild !== true ) {
  39749. // Mark as pending and add to build queue
  39750. renderObjectData.pendingBuild = true;
  39751. this._buildQueue.push( () => {
  39752. return this.getForRenderAsync( renderObject ).then( () => {
  39753. renderObjectData.pendingBuild = false;
  39754. } );
  39755. } );
  39756. // Start processing queue if not already running
  39757. this._processBuildQueue();
  39758. }
  39759. return null; // Not ready
  39760. }
  39761. /**
  39762. * Processes the build queue one item at a time.
  39763. * This ensures builds don't all run simultaneously and freeze the main thread.
  39764. *
  39765. * @private
  39766. */
  39767. _processBuildQueue() {
  39768. if ( this._buildInProgress || this._buildQueue.length === 0 ) {
  39769. return;
  39770. }
  39771. this._buildInProgress = true;
  39772. const buildFn = this._buildQueue.shift();
  39773. buildFn().then( () => {
  39774. this._buildInProgress = false;
  39775. // Process next item in queue
  39776. this._processBuildQueue();
  39777. } );
  39778. }
  39779. /**
  39780. * Deletes the given object from the internal data map
  39781. *
  39782. * @param {any} object - The object to delete.
  39783. * @return {?Object} The deleted dictionary.
  39784. */
  39785. delete( object ) {
  39786. if ( object.isRenderObject ) {
  39787. const nodeBuilderState = this.get( object ).nodeBuilderState;
  39788. if ( nodeBuilderState !== undefined ) {
  39789. nodeBuilderState.usedTimes --;
  39790. if ( nodeBuilderState.usedTimes === 0 ) {
  39791. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  39792. }
  39793. }
  39794. }
  39795. return super.delete( object );
  39796. }
  39797. /**
  39798. * Returns a node builder state for the given compute node.
  39799. *
  39800. * @param {Node} computeNode - The compute node.
  39801. * @return {NodeBuilderState} The node builder state.
  39802. */
  39803. getForCompute( computeNode ) {
  39804. const computeData = this.get( computeNode );
  39805. let nodeBuilderState = computeData.nodeBuilderState;
  39806. if ( nodeBuilderState === undefined || computeData.version !== computeNode.version ) {
  39807. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  39808. nodeBuilder.build();
  39809. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  39810. computeData.nodeBuilderState = nodeBuilderState;
  39811. computeData.version = computeNode.version;
  39812. }
  39813. return nodeBuilderState;
  39814. }
  39815. /**
  39816. * Creates a node builder state for the given node builder.
  39817. *
  39818. * @private
  39819. * @param {NodeBuilder} nodeBuilder - The node builder.
  39820. * @return {NodeBuilderState} The node builder state.
  39821. */
  39822. _createNodeBuilderState( nodeBuilder ) {
  39823. return new NodeBuilderState(
  39824. nodeBuilder.vertexShader,
  39825. nodeBuilder.fragmentShader,
  39826. nodeBuilder.computeShader,
  39827. nodeBuilder.getAttributesArray(),
  39828. nodeBuilder.getBindings(),
  39829. nodeBuilder.updateNodes,
  39830. nodeBuilder.updateBeforeNodes,
  39831. nodeBuilder.updateAfterNodes,
  39832. nodeBuilder.observer,
  39833. nodeBuilder.hardwareClipping,
  39834. nodeBuilder.transforms
  39835. );
  39836. }
  39837. /**
  39838. * Returns an environment node for the current configured
  39839. * scene environment.
  39840. *
  39841. * @param {Scene} scene - The scene.
  39842. * @return {Node} A node representing the current scene environment.
  39843. */
  39844. getEnvironmentNode( scene ) {
  39845. if ( this.renderer.lighting.enabled === false ) return null;
  39846. this.updateEnvironment( scene );
  39847. let environmentNode = null;
  39848. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  39849. environmentNode = scene.environmentNode;
  39850. } else {
  39851. const sceneData = this.get( scene );
  39852. if ( sceneData.environmentNode ) {
  39853. environmentNode = sceneData.environmentNode;
  39854. }
  39855. }
  39856. return environmentNode;
  39857. }
  39858. /**
  39859. * Returns a background node for the current configured
  39860. * scene background.
  39861. *
  39862. * @param {Scene} scene - The scene.
  39863. * @return {Node} A node representing the current scene background.
  39864. */
  39865. getBackgroundNode( scene ) {
  39866. this.updateBackground( scene );
  39867. let backgroundNode = null;
  39868. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  39869. backgroundNode = scene.backgroundNode;
  39870. } else {
  39871. const sceneData = this.get( scene );
  39872. if ( sceneData.backgroundNode ) {
  39873. backgroundNode = sceneData.backgroundNode;
  39874. }
  39875. }
  39876. return backgroundNode;
  39877. }
  39878. /**
  39879. * Returns a fog node for the current configured scene fog.
  39880. *
  39881. * @param {Scene} scene - The scene.
  39882. * @return {Node} A node representing the current scene fog.
  39883. */
  39884. getFogNode( scene ) {
  39885. this.updateFog( scene );
  39886. return scene.fogNode || this.get( scene ).fogNode || null;
  39887. }
  39888. /**
  39889. * Returns a cache key for the given scene and lights node.
  39890. * This key is used by `RenderObject` as a part of the dynamic
  39891. * cache key (a key that must be checked every time the render
  39892. * objects is drawn).
  39893. *
  39894. * @param {Scene} scene - The scene.
  39895. * @param {LightsNode} lightsNode - The lights node.
  39896. * @return {number} The cache key.
  39897. */
  39898. getCacheKey( scene, lightsNode ) {
  39899. _chainKeys$1[ 0 ] = scene;
  39900. _chainKeys$1[ 1 ] = lightsNode;
  39901. const callId = this.renderer.info.calls;
  39902. const cacheKeyData = this.callHashCache.get( _chainKeys$1 ) || {};
  39903. if ( cacheKeyData.callId !== callId ) {
  39904. _cacheKeyValues.push( this.renderer.getOutputRenderTarget() && this.renderer.getOutputRenderTarget().multiview ? 1 : 0 );
  39905. _cacheKeyValues.push( this.renderer.lighting.enabled ? 1 : 0 );
  39906. if ( this.renderer.lighting.enabled ) {
  39907. _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  39908. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  39909. _cacheKeyValues.push( this.renderer.shadowMap.type );
  39910. const environmentNode = this.getEnvironmentNode( scene );
  39911. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  39912. }
  39913. const fogNode = this.getFogNode( scene );
  39914. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  39915. cacheKeyData.callId = callId;
  39916. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  39917. this.callHashCache.set( _chainKeys$1, cacheKeyData );
  39918. _cacheKeyValues.length = 0;
  39919. }
  39920. _chainKeys$1[ 0 ] = null;
  39921. _chainKeys$1[ 1 ] = null;
  39922. return cacheKeyData.cacheKey;
  39923. }
  39924. /**
  39925. * A boolean that indicates whether tone mapping should be enabled
  39926. * or not.
  39927. *
  39928. * @type {boolean}
  39929. */
  39930. get isToneMappingState() {
  39931. return this.renderer.getRenderTarget() ? false : true;
  39932. }
  39933. /**
  39934. * If a scene background is configured, this method makes sure to
  39935. * represent the background with a corresponding node-based implementation.
  39936. *
  39937. * @param {Scene} scene - The scene.
  39938. */
  39939. updateBackground( scene ) {
  39940. const sceneData = this.get( scene );
  39941. const background = scene.background;
  39942. if ( background ) {
  39943. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  39944. if ( sceneData.background !== background || forceUpdate ) {
  39945. const backgroundNode = this.getCacheNode( 'background', background, () => {
  39946. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  39947. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  39948. return pmremTexture( background );
  39949. } else {
  39950. let envMap;
  39951. if ( background.isCubeTexture === true ) {
  39952. envMap = cubeTexture( background );
  39953. } else {
  39954. envMap = texture( background );
  39955. }
  39956. return cubeMapNode( envMap );
  39957. }
  39958. } else if ( background.isTexture === true ) {
  39959. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  39960. } else if ( background.isColor !== true ) {
  39961. error( 'WebGPUNodes: Unsupported background configuration.', background );
  39962. }
  39963. }, forceUpdate );
  39964. sceneData.backgroundNode = backgroundNode;
  39965. sceneData.background = background;
  39966. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  39967. }
  39968. } else if ( sceneData.backgroundNode ) {
  39969. delete sceneData.backgroundNode;
  39970. delete sceneData.background;
  39971. }
  39972. }
  39973. /**
  39974. * This method is part of the caching of nodes which are used to represents the
  39975. * scene's background, fog or environment.
  39976. *
  39977. * @param {string} type - The type of object to cache.
  39978. * @param {Object} object - The object.
  39979. * @param {Function} callback - A callback that produces a node representation for the given object.
  39980. * @param {boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  39981. * @return {Node} The node representation.
  39982. */
  39983. getCacheNode( type, object, callback, forceUpdate = false ) {
  39984. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  39985. let node = nodeCache.get( object );
  39986. if ( node === undefined || forceUpdate ) {
  39987. node = callback();
  39988. nodeCache.set( object, node );
  39989. }
  39990. return node;
  39991. }
  39992. /**
  39993. * If a scene fog is configured, this method makes sure to
  39994. * represent the fog with a corresponding node-based implementation.
  39995. *
  39996. * @param {Scene} scene - The scene.
  39997. */
  39998. updateFog( scene ) {
  39999. const sceneData = this.get( scene );
  40000. const sceneFog = scene.fog;
  40001. if ( sceneFog ) {
  40002. if ( sceneData.fog !== sceneFog ) {
  40003. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  40004. if ( sceneFog.isFogExp2 ) {
  40005. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  40006. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  40007. return fog( color, densityFogFactor( density ) );
  40008. } else if ( sceneFog.isFog ) {
  40009. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  40010. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  40011. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  40012. return fog( color, rangeFogFactor( near, far ) );
  40013. } else {
  40014. error( 'Renderer: Unsupported fog configuration.', sceneFog );
  40015. }
  40016. } );
  40017. sceneData.fogNode = fogNode;
  40018. sceneData.fog = sceneFog;
  40019. }
  40020. } else {
  40021. delete sceneData.fogNode;
  40022. delete sceneData.fog;
  40023. }
  40024. }
  40025. /**
  40026. * If a scene environment is configured, this method makes sure to
  40027. * represent the environment with a corresponding node-based implementation.
  40028. *
  40029. * @param {Scene} scene - The scene.
  40030. */
  40031. updateEnvironment( scene ) {
  40032. const sceneData = this.get( scene );
  40033. const environment = scene.environment;
  40034. if ( environment ) {
  40035. if ( sceneData.environment !== environment ) {
  40036. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  40037. if ( environment.isCubeTexture === true ) {
  40038. return cubeTexture( environment );
  40039. } else if ( environment.isTexture === true ) {
  40040. return texture( environment );
  40041. } else {
  40042. error( 'Nodes: Unsupported environment configuration.', environment );
  40043. }
  40044. } );
  40045. sceneData.environmentNode = environmentNode;
  40046. sceneData.environment = environment;
  40047. }
  40048. } else if ( sceneData.environmentNode ) {
  40049. delete sceneData.environmentNode;
  40050. delete sceneData.environment;
  40051. }
  40052. }
  40053. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  40054. const nodeFrame = this.nodeFrame;
  40055. nodeFrame.renderer = renderer;
  40056. nodeFrame.scene = scene;
  40057. nodeFrame.object = object;
  40058. nodeFrame.camera = camera;
  40059. nodeFrame.material = material;
  40060. return nodeFrame;
  40061. }
  40062. getNodeFrameForRender( renderObject ) {
  40063. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  40064. }
  40065. /**
  40066. * Returns the current output cache key.
  40067. *
  40068. * @return {string} The output cache key.
  40069. */
  40070. getOutputCacheKey() {
  40071. const renderer = this.renderer;
  40072. return renderer.toneMapping + ',' + renderer.currentColorSpace + ',' + renderer.xr.isPresenting;
  40073. }
  40074. /**
  40075. * Returns a node that represents the output configuration (tone mapping and
  40076. * color space) for the current target.
  40077. *
  40078. * @param {Texture} outputTarget - The output target.
  40079. * @return {Node} The output node.
  40080. */
  40081. getOutputNode( outputTarget ) {
  40082. const renderer = this.renderer;
  40083. let output;
  40084. if ( outputTarget.isArrayTexture ) {
  40085. if ( this.backend.isWebGLBackend ) {
  40086. output = texture( outputTarget, screenUV ).depth( builtin( 'gl_ViewID_OVR' ) ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  40087. } else {
  40088. output = texture( outputTarget, screenUV ).depth( _outputLayerIndex ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  40089. }
  40090. } else {
  40091. output = texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  40092. }
  40093. return output;
  40094. }
  40095. /**
  40096. * Sets the output layer index for array texture output pass.
  40097. * This should be called before each layer render during the output pass.
  40098. *
  40099. * @param {number} index - The layer index.
  40100. */
  40101. setOutputLayerIndex( index ) {
  40102. _outputLayerIndex.value = index;
  40103. }
  40104. /**
  40105. * Triggers the call of `updateBefore()` methods
  40106. * for all nodes of the given render object.
  40107. *
  40108. * @param {RenderObject} renderObject - The render object.
  40109. */
  40110. updateBefore( renderObject ) {
  40111. const nodeBuilder = renderObject.getNodeBuilderState();
  40112. for ( const node of nodeBuilder.updateBeforeNodes ) {
  40113. // update frame state for each node
  40114. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  40115. }
  40116. }
  40117. /**
  40118. * Triggers the call of `updateAfter()` methods
  40119. * for all nodes of the given render object.
  40120. *
  40121. * @param {RenderObject} renderObject - The render object.
  40122. */
  40123. updateAfter( renderObject ) {
  40124. const nodeBuilder = renderObject.getNodeBuilderState();
  40125. for ( const node of nodeBuilder.updateAfterNodes ) {
  40126. // update frame state for each node
  40127. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  40128. }
  40129. }
  40130. /**
  40131. * Triggers the call of `update()` methods
  40132. * for all nodes of the given compute node.
  40133. *
  40134. * @param {Node} computeNode - The compute node.
  40135. */
  40136. updateForCompute( computeNode ) {
  40137. const nodeFrame = this.getNodeFrame();
  40138. const nodeBuilder = this.getForCompute( computeNode );
  40139. for ( const node of nodeBuilder.updateNodes ) {
  40140. nodeFrame.updateNode( node );
  40141. }
  40142. }
  40143. /**
  40144. * Triggers the call of `update()` methods
  40145. * for all nodes of the given render object.
  40146. *
  40147. * @param {RenderObject} renderObject - The render object.
  40148. */
  40149. updateForRender( renderObject ) {
  40150. const nodeFrame = this.getNodeFrameForRender( renderObject );
  40151. const nodeBuilder = renderObject.getNodeBuilderState();
  40152. for ( const node of nodeBuilder.updateNodes ) {
  40153. nodeFrame.updateNode( node );
  40154. }
  40155. }
  40156. /**
  40157. * Returns `true` if the given render object requires a refresh.
  40158. *
  40159. * @param {RenderObject} renderObject - The render object.
  40160. * @return {boolean} Whether the given render object requires a refresh or not.
  40161. */
  40162. needsRefresh( renderObject ) {
  40163. const nodeFrame = this.getNodeFrameForRender( renderObject );
  40164. const monitor = renderObject.getMonitor();
  40165. return monitor.needsRefresh( renderObject, nodeFrame );
  40166. }
  40167. /**
  40168. * Frees the internal resources.
  40169. */
  40170. dispose() {
  40171. super.dispose();
  40172. this.nodeFrame = new NodeFrame();
  40173. this.nodeBuilderCache = new Map();
  40174. this.cacheLib = {};
  40175. }
  40176. }
  40177. const _plane = /*@__PURE__*/ new Plane();
  40178. /**
  40179. * Represents the state that is used to perform clipping via clipping planes.
  40180. * There is a default clipping context for each render context. When the
  40181. * scene holds instances of `ClippingGroup`, there will be a context for each
  40182. * group.
  40183. *
  40184. * @private
  40185. */
  40186. class ClippingContext {
  40187. /**
  40188. * Constructs a new clipping context.
  40189. *
  40190. * @param {?ClippingContext} [parentContext=null] - A reference to the parent clipping context.
  40191. */
  40192. constructor( parentContext = null ) {
  40193. /**
  40194. * The clipping context's version.
  40195. *
  40196. * @type {number}
  40197. * @readonly
  40198. */
  40199. this.version = 0;
  40200. /**
  40201. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  40202. *
  40203. * @type {?boolean}
  40204. * @default null
  40205. */
  40206. this.clipIntersection = null;
  40207. /**
  40208. * The clipping context's cache key.
  40209. *
  40210. * @type {string}
  40211. */
  40212. this.cacheKey = '';
  40213. /**
  40214. * Whether the shadow pass is active or not.
  40215. *
  40216. * @type {boolean}
  40217. * @default false
  40218. */
  40219. this.shadowPass = false;
  40220. /**
  40221. * The view matrix.
  40222. *
  40223. * @type {Matrix4}
  40224. */
  40225. this.viewMatrix = new Matrix4();
  40226. /**
  40227. * The view normal matrix.
  40228. *
  40229. * @type {Matrix3}
  40230. */
  40231. this.viewNormalMatrix = new Matrix3();
  40232. /**
  40233. * Internal cache for maintaining clipping contexts.
  40234. *
  40235. * @type {WeakMap<ClippingGroup,ClippingContext>}
  40236. */
  40237. this.clippingGroupContexts = new WeakMap();
  40238. /**
  40239. * The intersection planes.
  40240. *
  40241. * @type {Array<Vector4>}
  40242. */
  40243. this.intersectionPlanes = [];
  40244. /**
  40245. * The intersection planes.
  40246. *
  40247. * @type {Array<Vector4>}
  40248. */
  40249. this.unionPlanes = [];
  40250. /**
  40251. * The version of the clipping context's parent context.
  40252. *
  40253. * @type {?number}
  40254. * @readonly
  40255. */
  40256. this.parentVersion = null;
  40257. if ( parentContext !== null ) {
  40258. this.viewMatrix = parentContext.viewMatrix;
  40259. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  40260. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  40261. this.shadowPass = parentContext.shadowPass;
  40262. }
  40263. }
  40264. /**
  40265. * Projects the given source clipping planes and writes the result into the
  40266. * destination array.
  40267. *
  40268. * @param {Array<Plane>} source - The source clipping planes.
  40269. * @param {Array<Vector4>} destination - The destination.
  40270. * @param {number} offset - The offset.
  40271. */
  40272. projectPlanes( source, destination, offset ) {
  40273. const l = source.length;
  40274. for ( let i = 0; i < l; i ++ ) {
  40275. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  40276. const v = destination[ offset + i ];
  40277. const normal = _plane.normal;
  40278. v.x = - normal.x;
  40279. v.y = - normal.y;
  40280. v.z = - normal.z;
  40281. v.w = _plane.constant;
  40282. }
  40283. }
  40284. /**
  40285. * Updates the root clipping context of a scene.
  40286. *
  40287. * @param {Scene} scene - The scene.
  40288. * @param {Camera} camera - The camera that is used to render the scene.
  40289. */
  40290. updateGlobal( scene, camera ) {
  40291. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  40292. this.viewMatrix.copy( camera.matrixWorldInverse );
  40293. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  40294. }
  40295. /**
  40296. * Updates the clipping context.
  40297. *
  40298. * @param {ClippingContext} parentContext - The parent context.
  40299. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  40300. */
  40301. update( parentContext, clippingGroup ) {
  40302. let update = false;
  40303. if ( parentContext.version !== this.parentVersion ) {
  40304. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  40305. this.unionPlanes = Array.from( parentContext.unionPlanes );
  40306. this.parentVersion = parentContext.version;
  40307. }
  40308. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  40309. this.clipIntersection = clippingGroup.clipIntersection;
  40310. if ( this.clipIntersection ) {
  40311. this.unionPlanes.length = parentContext.unionPlanes.length;
  40312. } else {
  40313. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  40314. }
  40315. }
  40316. const srcClippingPlanes = clippingGroup.clippingPlanes;
  40317. const l = srcClippingPlanes.length;
  40318. let dstClippingPlanes;
  40319. let offset;
  40320. if ( this.clipIntersection ) {
  40321. dstClippingPlanes = this.intersectionPlanes;
  40322. offset = parentContext.intersectionPlanes.length;
  40323. } else {
  40324. dstClippingPlanes = this.unionPlanes;
  40325. offset = parentContext.unionPlanes.length;
  40326. }
  40327. if ( dstClippingPlanes.length !== offset + l ) {
  40328. dstClippingPlanes.length = offset + l;
  40329. for ( let i = 0; i < l; i ++ ) {
  40330. dstClippingPlanes[ offset + i ] = new Vector4();
  40331. }
  40332. update = true;
  40333. }
  40334. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  40335. if ( update ) {
  40336. this.version ++;
  40337. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  40338. }
  40339. }
  40340. /**
  40341. * Returns a clipping context for the given clipping group.
  40342. *
  40343. * @param {ClippingGroup} clippingGroup - The clipping group.
  40344. * @return {ClippingContext} The clipping context.
  40345. */
  40346. getGroupContext( clippingGroup ) {
  40347. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  40348. let context = this.clippingGroupContexts.get( clippingGroup );
  40349. if ( context === undefined ) {
  40350. context = new ClippingContext( this );
  40351. this.clippingGroupContexts.set( clippingGroup, context );
  40352. }
  40353. context.update( this, clippingGroup );
  40354. return context;
  40355. }
  40356. /**
  40357. * The count of union clipping planes.
  40358. *
  40359. * @type {number}
  40360. * @readonly
  40361. */
  40362. get unionClippingCount() {
  40363. return this.unionPlanes.length;
  40364. }
  40365. }
  40366. /**
  40367. * This module is used to represent render bundles inside the renderer
  40368. * for further processing.
  40369. *
  40370. * @private
  40371. */
  40372. class RenderBundle {
  40373. /**
  40374. * Constructs a new bundle group.
  40375. *
  40376. * @param {BundleGroup} bundleGroup - The bundle group.
  40377. * @param {Camera} camera - The camera the bundle group is rendered with.
  40378. * @param {RenderContext} renderContext - The render context the bundle is rendered with.
  40379. */
  40380. constructor( bundleGroup, camera, renderContext ) {
  40381. this.bundleGroup = bundleGroup;
  40382. this.camera = camera;
  40383. this.renderContext = renderContext;
  40384. }
  40385. }
  40386. const _chainKeys = [];
  40387. /**
  40388. * This renderer module manages render bundles.
  40389. *
  40390. * @private
  40391. */
  40392. class RenderBundles {
  40393. /**
  40394. * Constructs a new render bundle management component.
  40395. */
  40396. constructor() {
  40397. /**
  40398. * A chain map for maintaining the render bundles.
  40399. *
  40400. * @type {ChainMap}
  40401. */
  40402. this.bundles = new ChainMap();
  40403. }
  40404. /**
  40405. * Returns a render bundle for the given bundle group and camera.
  40406. *
  40407. * @param {BundleGroup} bundleGroup - The bundle group.
  40408. * @param {Camera} camera - The camera the bundle group is rendered with.
  40409. * @param {RenderContext} renderContext - The render context the bundle is rendered with.
  40410. * @return {RenderBundle} The render bundle.
  40411. */
  40412. get( bundleGroup, camera, renderContext ) {
  40413. const bundles = this.bundles;
  40414. _chainKeys[ 0 ] = bundleGroup;
  40415. _chainKeys[ 1 ] = camera;
  40416. _chainKeys[ 2 ] = renderContext;
  40417. let bundle = bundles.get( _chainKeys );
  40418. if ( bundle === undefined ) {
  40419. bundle = new RenderBundle( bundleGroup, camera, renderContext );
  40420. bundles.set( _chainKeys, bundle );
  40421. }
  40422. _chainKeys[ 0 ] = null;
  40423. _chainKeys[ 1 ] = null;
  40424. _chainKeys[ 2 ] = null;
  40425. return bundle;
  40426. }
  40427. /**
  40428. * Frees all internal resources.
  40429. */
  40430. dispose() {
  40431. this.bundles = new ChainMap();
  40432. }
  40433. }
  40434. /**
  40435. * The purpose of a node library is to assign node implementations
  40436. * to existing library features. In `WebGPURenderer` lights, materials
  40437. * which are not based on `NodeMaterial` as well as tone mapping techniques
  40438. * are implemented with node-based modules.
  40439. *
  40440. * @private
  40441. */
  40442. class NodeLibrary {
  40443. /**
  40444. * Constructs a new node library.
  40445. */
  40446. constructor() {
  40447. /**
  40448. * A weak map that maps lights to light nodes.
  40449. *
  40450. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  40451. */
  40452. this.lightNodes = new WeakMap();
  40453. /**
  40454. * A map that maps materials to node materials.
  40455. *
  40456. * @type {Map<string,NodeMaterial.constructor>}
  40457. */
  40458. this.materialNodes = new Map();
  40459. /**
  40460. * A map that maps tone mapping techniques (constants)
  40461. * to tone mapping node functions.
  40462. *
  40463. * @type {Map<number,Function>}
  40464. */
  40465. this.toneMappingNodes = new Map();
  40466. }
  40467. /**
  40468. * Returns a matching node material instance for the given material object.
  40469. *
  40470. * This method also assigns/copies the properties of the given material object
  40471. * to the node material. This is done to make sure the current material
  40472. * configuration carries over to the node version.
  40473. *
  40474. * @param {Material} material - A material.
  40475. * @return {NodeMaterial} The corresponding node material.
  40476. */
  40477. fromMaterial( material ) {
  40478. if ( material.isNodeMaterial ) return material;
  40479. let nodeMaterial = null;
  40480. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  40481. if ( nodeMaterialClass !== null ) {
  40482. nodeMaterial = new nodeMaterialClass();
  40483. for ( const key in material ) {
  40484. nodeMaterial[ key ] = material[ key ];
  40485. }
  40486. }
  40487. return nodeMaterial;
  40488. }
  40489. /**
  40490. * Adds a tone mapping node function for a tone mapping technique (constant).
  40491. *
  40492. * @param {Function} toneMappingNode - The tone mapping node function.
  40493. * @param {number} toneMapping - The tone mapping.
  40494. */
  40495. addToneMapping( toneMappingNode, toneMapping ) {
  40496. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  40497. }
  40498. /**
  40499. * Returns a tone mapping node function for a tone mapping technique (constant).
  40500. *
  40501. * @param {number} toneMapping - The tone mapping.
  40502. * @return {?Function} The tone mapping node function. Returns `null` if no node function is found.
  40503. */
  40504. getToneMappingFunction( toneMapping ) {
  40505. return this.toneMappingNodes.get( toneMapping ) || null;
  40506. }
  40507. /**
  40508. * Returns a node material class definition for a material type.
  40509. *
  40510. * @param {string} materialType - The material type.
  40511. * @return {?NodeMaterial.constructor} The node material class definition. Returns `null` if no node material is found.
  40512. */
  40513. getMaterialNodeClass( materialType ) {
  40514. return this.materialNodes.get( materialType ) || null;
  40515. }
  40516. /**
  40517. * Adds a node material class definition for a given material type.
  40518. *
  40519. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  40520. * @param {string} materialClassType - The material type.
  40521. */
  40522. addMaterial( materialNodeClass, materialClassType ) {
  40523. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  40524. }
  40525. /**
  40526. * Returns a light node class definition for a light class definition.
  40527. *
  40528. * @param {Light.constructor} light - The light class definition.
  40529. * @return {?AnalyticLightNode.constructor} The light node class definition. Returns `null` if no light node is found.
  40530. */
  40531. getLightNodeClass( light ) {
  40532. return this.lightNodes.get( light ) || null;
  40533. }
  40534. /**
  40535. * Adds a light node class definition for a given light class definition.
  40536. *
  40537. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  40538. * @param {Light.constructor} lightClass - The light class definition.
  40539. */
  40540. addLight( lightNodeClass, lightClass ) {
  40541. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  40542. }
  40543. /**
  40544. * Adds a node class definition for the given type to the provided type library.
  40545. *
  40546. * @param {Node.constructor} nodeClass - The node class definition.
  40547. * @param {number|string} type - The object type.
  40548. * @param {Map<number|string,Node.constructor>} library - The type library.
  40549. */
  40550. addType( nodeClass, type, library ) {
  40551. if ( library.has( type ) ) {
  40552. warn( `Redefinition of node ${ type }` );
  40553. return;
  40554. }
  40555. if ( typeof nodeClass !== 'function' ) throw new Error( `THREE.NodeLibrary: Node class ${ nodeClass.name } is not a class.` );
  40556. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `THREE.NodeLibrary: Base class ${ type } is not a class.` );
  40557. library.set( type, nodeClass );
  40558. }
  40559. /**
  40560. * Adds a node class definition for the given class definition to the provided type library.
  40561. *
  40562. * @param {Node.constructor} nodeClass - The node class definition.
  40563. * @param {Node.constructor} baseClass - The class definition.
  40564. * @param {WeakMap<Node.constructor, Node.constructor>} library - The type library.
  40565. */
  40566. addClass( nodeClass, baseClass, library ) {
  40567. if ( library.has( baseClass ) ) {
  40568. warn( `Redefinition of node ${ baseClass.name }` );
  40569. return;
  40570. }
  40571. if ( typeof nodeClass !== 'function' ) throw new Error( `THREE.NodeLibrary: Node class ${ nodeClass.name } is not a class.` );
  40572. if ( typeof baseClass !== 'function' ) throw new Error( `THREE.NodeLibrary: Base class ${ baseClass.name } is not a class.` );
  40573. library.set( baseClass, nodeClass );
  40574. }
  40575. }
  40576. const _defaultLights = /*@__PURE__*/ new LightsNode();
  40577. const _weakMap = /*@__PURE__*/ new WeakMap();
  40578. /**
  40579. * This renderer module manages the lights nodes which are unique
  40580. * per scene and camera combination.
  40581. *
  40582. * The lights node itself is later configured in the render list
  40583. * with the actual lights from the scene.
  40584. *
  40585. * @private
  40586. */
  40587. class Lighting {
  40588. /**
  40589. * Constructs a new lighting manager.
  40590. */
  40591. constructor() {
  40592. /**
  40593. * Whether this lighting manager is enabled or not.
  40594. *
  40595. * @type {boolean}
  40596. * @default true
  40597. */
  40598. this.enabled = true;
  40599. /**
  40600. * A stack of light arrays saved per render via {@link Lighting#beginRender}.
  40601. *
  40602. * @private
  40603. * @type {Array<Array<Light>>}
  40604. */
  40605. this._cache = [];
  40606. }
  40607. /**
  40608. * Creates a new lights node for the given array of lights.
  40609. *
  40610. * @param {Array<Light>} lights - The render object.
  40611. * @return {LightsNode} The lights node.
  40612. */
  40613. createNode( lights = [] ) {
  40614. return new LightsNode().setLights( lights );
  40615. }
  40616. /**
  40617. * Returns a lights node for the given scene.
  40618. *
  40619. * @param {Scene} scene - The scene.
  40620. * @return {LightsNode} The lights node.
  40621. */
  40622. getNode( scene ) {
  40623. // Ignore renderable objects, e.g: Mesh, Sprite, etc.
  40624. if ( scene.isScene !== true && scene.isGroup !== true ) return _defaultLights;
  40625. let node = _weakMap.get( scene );
  40626. if ( node === undefined ) {
  40627. node = this.createNode();
  40628. _weakMap.set( scene, node );
  40629. }
  40630. return node;
  40631. }
  40632. /**
  40633. * Saves the current lights of the scene's lights node so they can be restored
  40634. * in {@link Lighting#finishRender}. Must be paired with a `finishRender()` call
  40635. * to avoid memory leaks.
  40636. *
  40637. * Nested render calls might mutate the lights array so a save/restore is required
  40638. * for each render call.
  40639. *
  40640. * @param {Scene} scene - The scene.
  40641. */
  40642. beginRender( scene ) {
  40643. this._cache.push( this.getNode( scene ).getLights() );
  40644. }
  40645. /**
  40646. * Restores the lights saved by the matching {@link Lighting#beginRender} call.
  40647. *
  40648. * @param {Scene} scene - The scene.
  40649. */
  40650. finishRender( scene ) {
  40651. this.getNode( scene ).setLights( this._cache.pop() );
  40652. }
  40653. }
  40654. /**
  40655. * A special type of render target that is used when rendering
  40656. * with the WebXR Device API.
  40657. *
  40658. * @private
  40659. * @augments RenderTarget
  40660. */
  40661. class XRRenderTarget extends RenderTarget {
  40662. /**
  40663. * Constructs a new XR render target.
  40664. *
  40665. * @param {number} [width=1] - The width of the render target.
  40666. * @param {number} [height=1] - The height of the render target.
  40667. * @param {Object} [options={}] - The configuration options.
  40668. */
  40669. constructor( width = 1, height = 1, options = {} ) {
  40670. super( width, height, options );
  40671. /**
  40672. * This flag can be used for type testing.
  40673. *
  40674. * @type {boolean}
  40675. * @readonly
  40676. * @default true
  40677. */
  40678. this.isXRRenderTarget = true;
  40679. /**
  40680. * Whether the attachments of the render target
  40681. * are defined by external textures. This flag is
  40682. * set to `true` when using the WebXR Layers API.
  40683. *
  40684. * @private
  40685. * @type {boolean}
  40686. * @default false
  40687. */
  40688. this._hasExternalTextures = false;
  40689. /**
  40690. * Whether a depth buffer should automatically be allocated
  40691. * for this XR render target or not.
  40692. *
  40693. * Allocating a depth buffer is the default behavior of XR render
  40694. * targets. However, when using the WebXR Layers API, this flag
  40695. * must be set to `false` when the `ignoreDepthValues` property of
  40696. * the projection layers evaluates to `false`.
  40697. *
  40698. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  40699. *
  40700. * @private
  40701. * @type {boolean}
  40702. * @default true
  40703. */
  40704. this._autoAllocateDepthBuffer = true;
  40705. /**
  40706. * Whether this render target is associated with a XRWebGLLayer.
  40707. *
  40708. * A XRWebGLLayer points to an opaque framebuffer. Basically,
  40709. * this means that you don't have access to its bound color,
  40710. * stencil and depth buffers. We need to handle this framebuffer
  40711. * differently since its textures are always bound.
  40712. *
  40713. * @private
  40714. * @type {boolean}
  40715. * @default false
  40716. * */
  40717. this._isOpaqueFramebuffer = false;
  40718. }
  40719. copy( source ) {
  40720. super.copy( source );
  40721. this._hasExternalTextures = source._hasExternalTextures;
  40722. this._autoAllocateDepthBuffer = source._autoAllocateDepthBuffer;
  40723. this._isOpaqueFramebuffer = source._isOpaqueFramebuffer;
  40724. return this;
  40725. }
  40726. }
  40727. const _cameraLPos = /*@__PURE__*/ new Vector3();
  40728. const _cameraRPos = /*@__PURE__*/ new Vector3();
  40729. const _contextNodeLib = /*@__PURE__*/ new WeakMap();
  40730. /**
  40731. * The XR manager is built on top of the WebXR Device API to
  40732. * manage XR sessions with renderer backends.
  40733. *
  40734. * @augments EventDispatcher
  40735. */
  40736. class XRManager extends EventDispatcher {
  40737. /**
  40738. * Constructs a new XR manager.
  40739. *
  40740. * @param {Renderer} renderer - The renderer.
  40741. * @param {boolean} [multiview=false] - Enables multiview if the device supports it.
  40742. */
  40743. constructor( renderer, multiview = false ) {
  40744. super();
  40745. /**
  40746. * This flag globally enables XR rendering.
  40747. *
  40748. * @type {boolean}
  40749. * @default false
  40750. */
  40751. this.enabled = false;
  40752. /**
  40753. * Whether the XR device is currently presenting or not.
  40754. *
  40755. * @type {boolean}
  40756. * @default false
  40757. * @readonly
  40758. */
  40759. this.isPresenting = false;
  40760. /**
  40761. * Whether the XR camera should automatically be updated or not.
  40762. *
  40763. * @type {boolean}
  40764. * @default true
  40765. */
  40766. this.cameraAutoUpdate = true;
  40767. /**
  40768. * The renderer.
  40769. *
  40770. * @private
  40771. * @type {Renderer}
  40772. */
  40773. this._renderer = renderer;
  40774. // camera
  40775. /**
  40776. * Represents the camera for the left eye.
  40777. *
  40778. * @private
  40779. * @type {PerspectiveCamera}
  40780. */
  40781. this._cameraL = new PerspectiveCamera();
  40782. this._cameraL.viewport = new Vector4();
  40783. this._cameraL.matrixWorldAutoUpdate = false;
  40784. /**
  40785. * Represents the camera for the right eye.
  40786. *
  40787. * @private
  40788. * @type {PerspectiveCamera}
  40789. */
  40790. this._cameraR = new PerspectiveCamera();
  40791. this._cameraR.viewport = new Vector4();
  40792. this._cameraR.matrixWorldAutoUpdate = false;
  40793. /**
  40794. * A list of cameras used for rendering the XR views.
  40795. *
  40796. * @private
  40797. * @type {Array<Camera>}
  40798. */
  40799. this._cameras = [ this._cameraL, this._cameraR ];
  40800. /**
  40801. * The main XR camera.
  40802. *
  40803. * @private
  40804. * @type {ArrayCamera}
  40805. */
  40806. this._cameraXR = new ArrayCamera();
  40807. /**
  40808. * The current near value of the XR camera.
  40809. *
  40810. * @private
  40811. * @type {?number}
  40812. * @default null
  40813. */
  40814. this._currentDepthNear = null;
  40815. /**
  40816. * The current far value of the XR camera.
  40817. *
  40818. * @private
  40819. * @type {?number}
  40820. * @default null
  40821. */
  40822. this._currentDepthFar = null;
  40823. /**
  40824. * A list of WebXR controllers requested by the application.
  40825. *
  40826. * @private
  40827. * @type {Array<WebXRController>}
  40828. */
  40829. this._controllers = [];
  40830. /**
  40831. * A list of XR input source. Each input source belongs to
  40832. * an instance of WebXRController.
  40833. *
  40834. * @private
  40835. * @type {Array<XRInputSource?>}
  40836. */
  40837. this._controllerInputSources = [];
  40838. /**
  40839. * The XR render target that represents the rendering destination
  40840. * during an active XR session.
  40841. *
  40842. * @private
  40843. * @type {?RenderTarget}
  40844. * @default null
  40845. */
  40846. this._xrRenderTarget = null;
  40847. /**
  40848. * An array holding all the non-projection layers
  40849. *
  40850. * @private
  40851. * @type {Array<Object>}
  40852. * @default []
  40853. */
  40854. this._layers = [];
  40855. /**
  40856. * Whether the XR session uses layers.
  40857. *
  40858. * @private
  40859. * @type {boolean}
  40860. * @default false
  40861. */
  40862. this._sessionUsesLayers = false;
  40863. /**
  40864. * Whether the device supports binding gl objects.
  40865. *
  40866. * @private
  40867. * @type {boolean}
  40868. * @readonly
  40869. */
  40870. this._supportsGlBinding = typeof XRWebGLBinding !== 'undefined';
  40871. this._supportsWebGPUBinding = typeof globalThis.XRGPUBinding !== 'undefined';
  40872. /**
  40873. * Helper function to create native WebXR Layer.
  40874. *
  40875. * @private
  40876. * @type {Function}
  40877. */
  40878. this._createXRLayer = createXRLayer.bind( this );
  40879. /**
  40880. * The current WebGL context.
  40881. *
  40882. * @private
  40883. * @type {?WebGL2RenderingContext}
  40884. * @default null
  40885. */
  40886. this._gl = null;
  40887. /**
  40888. * The current animation context.
  40889. *
  40890. * @private
  40891. * @type {?Window}
  40892. * @default null
  40893. */
  40894. this._currentAnimationContext = null;
  40895. /**
  40896. * The current animation loop.
  40897. *
  40898. * @private
  40899. * @type {?Function}
  40900. * @default null
  40901. */
  40902. this._currentAnimationLoop = null;
  40903. /**
  40904. * The current pixel ratio.
  40905. *
  40906. * @private
  40907. * @type {?number}
  40908. * @default null
  40909. */
  40910. this._currentPixelRatio = null;
  40911. /**
  40912. * The renderer's sample count before XR temporarily overrides it.
  40913. *
  40914. * @private
  40915. * @type {?number}
  40916. * @default null
  40917. */
  40918. this._currentSamples = null;
  40919. /**
  40920. * The current size of the renderer's canvas
  40921. * in logical pixel unit.
  40922. *
  40923. * @private
  40924. * @type {Vector2}
  40925. */
  40926. this._currentSize = new Vector2();
  40927. /**
  40928. * The default event listener for handling events inside a XR session.
  40929. *
  40930. * @private
  40931. * @type {Function}
  40932. */
  40933. this._onSessionEvent = onSessionEvent.bind( this );
  40934. /**
  40935. * The event listener for handling the end of a XR session.
  40936. *
  40937. * @private
  40938. * @type {Function}
  40939. */
  40940. this._onSessionEnd = onSessionEnd.bind( this );
  40941. /**
  40942. * The event listener for handling the `inputsourceschange` event.
  40943. *
  40944. * @private
  40945. * @type {Function}
  40946. */
  40947. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  40948. /**
  40949. * The animation loop which is used as a replacement for the default
  40950. * animation loop of the application. It is only used when a XR session
  40951. * is active.
  40952. *
  40953. * @private
  40954. * @type {Function}
  40955. */
  40956. this._onAnimationFrame = onAnimationFrame.bind( this );
  40957. /**
  40958. * The current XR reference space.
  40959. *
  40960. * @private
  40961. * @type {?XRReferenceSpace}
  40962. * @default null
  40963. */
  40964. this._referenceSpace = null;
  40965. /**
  40966. * The current XR reference space type.
  40967. *
  40968. * @private
  40969. * @type {XRReferenceSpaceType}
  40970. * @default 'local-floor'
  40971. */
  40972. this._referenceSpaceType = 'local-floor';
  40973. /**
  40974. * A custom reference space defined by the application.
  40975. *
  40976. * @private
  40977. * @type {?XRReferenceSpace}
  40978. * @default null
  40979. */
  40980. this._customReferenceSpace = null;
  40981. /**
  40982. * The framebuffer scale factor.
  40983. *
  40984. * @private
  40985. * @type {number}
  40986. * @default 1
  40987. */
  40988. this._framebufferScaleFactor = 1;
  40989. /**
  40990. * The foveation factor.
  40991. *
  40992. * @private
  40993. * @type {number}
  40994. * @default 1
  40995. */
  40996. this._foveation = 1.0;
  40997. /**
  40998. * A reference to the current XR session.
  40999. *
  41000. * @private
  41001. * @type {?XRSession}
  41002. * @default null
  41003. */
  41004. this._session = null;
  41005. /**
  41006. * A reference to the current XR base layer.
  41007. *
  41008. * @private
  41009. * @type {?XRWebGLLayer}
  41010. * @default null
  41011. */
  41012. this._glBaseLayer = null;
  41013. /**
  41014. * A reference to the current XR binding.
  41015. *
  41016. * @private
  41017. * @type {?XRWebGLBinding}
  41018. * @default null
  41019. */
  41020. this._glBinding = null;
  41021. /**
  41022. * A reference to the current XR WebGPU binding.
  41023. *
  41024. * @private
  41025. * @type {?XRGPUBinding}
  41026. * @default null
  41027. */
  41028. this._webgpuBinding = null;
  41029. /**
  41030. * A reference to the current XR projection layer.
  41031. *
  41032. * @private
  41033. * @type {?XRProjectionLayer}
  41034. * @default null
  41035. */
  41036. this._glProjLayer = null;
  41037. /**
  41038. * A reference to the current XR frame.
  41039. *
  41040. * @private
  41041. * @type {?XRFrame}
  41042. * @default null
  41043. */
  41044. this._xrFrame = null;
  41045. /**
  41046. * Whether the browser supports the APIs necessary to use XRProjectionLayers.
  41047. *
  41048. * Note: this does not represent XRSession explicitly requesting
  41049. * `'layers'` as a feature - see `_sessionUsesLayers` and #30112
  41050. *
  41051. * @private
  41052. * @type {boolean}
  41053. * @readonly
  41054. */
  41055. this._supportsLayers = ( this._supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  41056. /**
  41057. * Whether the usage of multiview has been requested by the application or not.
  41058. *
  41059. * @private
  41060. * @type {boolean}
  41061. * @default false
  41062. * @readonly
  41063. */
  41064. this._useMultiviewIfPossible = multiview;
  41065. /**
  41066. * Whether the usage of multiview is actually enabled. This flag only evaluates to `true`
  41067. * if multiview has been requested by the application and the `OVR_multiview2` is available.
  41068. *
  41069. * @private
  41070. * @type {boolean}
  41071. * @readonly
  41072. */
  41073. this._useMultiview = false;
  41074. }
  41075. /**
  41076. * Returns an instance of `THREE.Group` that represents the transformation
  41077. * of a XR controller in target ray space. The requested controller is defined
  41078. * by the given index.
  41079. *
  41080. * @param {number} index - The index of the XR controller.
  41081. * @return {Group} A group that represents the controller's transformation.
  41082. */
  41083. getController( index ) {
  41084. const controller = this._getController( index );
  41085. return controller.getTargetRaySpace();
  41086. }
  41087. /**
  41088. * Returns an instance of `THREE.Group` that represents the transformation
  41089. * of a XR controller in grip space. The requested controller is defined
  41090. * by the given index.
  41091. *
  41092. * @param {number} index - The index of the XR controller.
  41093. * @return {Group} A group that represents the controller's transformation.
  41094. */
  41095. getControllerGrip( index ) {
  41096. const controller = this._getController( index );
  41097. return controller.getGripSpace();
  41098. }
  41099. /**
  41100. * Returns an instance of `THREE.Group` that represents the transformation
  41101. * of a XR controller in hand space. The requested controller is defined
  41102. * by the given index.
  41103. *
  41104. * @param {number} index - The index of the XR controller.
  41105. * @return {Group} A group that represents the controller's transformation.
  41106. */
  41107. getHand( index ) {
  41108. const controller = this._getController( index );
  41109. return controller.getHandSpace();
  41110. }
  41111. /**
  41112. * Returns the foveation value.
  41113. *
  41114. * @return {number|undefined} The foveation value.
  41115. */
  41116. getFoveation() {
  41117. return this._foveation;
  41118. }
  41119. /**
  41120. * Sets the foveation value.
  41121. *
  41122. * @param {number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  41123. * and `1` means maximum foveation (the edges render at lower resolution).
  41124. */
  41125. setFoveation( foveation ) {
  41126. this._foveation = foveation;
  41127. if ( this._glProjLayer !== null ) {
  41128. this._glProjLayer.fixedFoveation = foveation;
  41129. }
  41130. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  41131. this._glBaseLayer.fixedFoveation = foveation;
  41132. }
  41133. }
  41134. /**
  41135. * Returns the framebuffer scale factor.
  41136. *
  41137. * @return {number} The framebuffer scale factor.
  41138. */
  41139. getFramebufferScaleFactor() {
  41140. return this._framebufferScaleFactor;
  41141. }
  41142. /**
  41143. * Sets the framebuffer scale factor.
  41144. *
  41145. * This method can not be used during a XR session.
  41146. *
  41147. * @param {number} factor - The framebuffer scale factor.
  41148. */
  41149. setFramebufferScaleFactor( factor ) {
  41150. this._framebufferScaleFactor = factor;
  41151. if ( this.isPresenting === true ) {
  41152. warn( 'XRManager: Cannot change framebuffer scale while presenting.' );
  41153. }
  41154. }
  41155. /**
  41156. * Returns the reference space type.
  41157. *
  41158. * @return {XRReferenceSpaceType} The reference space type.
  41159. */
  41160. getReferenceSpaceType() {
  41161. return this._referenceSpaceType;
  41162. }
  41163. /**
  41164. * Sets the reference space type.
  41165. *
  41166. * This method can not be used during a XR session.
  41167. *
  41168. * @param {XRReferenceSpaceType} type - The reference space type.
  41169. */
  41170. setReferenceSpaceType( type ) {
  41171. this._referenceSpaceType = type;
  41172. if ( this.isPresenting === true ) {
  41173. warn( 'XRManager: Cannot change reference space type while presenting.' );
  41174. }
  41175. }
  41176. /**
  41177. * Returns the XR reference space.
  41178. *
  41179. * @return {XRReferenceSpace} The XR reference space.
  41180. */
  41181. getReferenceSpace() {
  41182. return this._customReferenceSpace || this._referenceSpace;
  41183. }
  41184. /**
  41185. * Sets a custom XR reference space.
  41186. *
  41187. * @param {XRReferenceSpace} space - The XR reference space.
  41188. */
  41189. setReferenceSpace( space ) {
  41190. this._customReferenceSpace = space;
  41191. }
  41192. /**
  41193. * Returns the XR camera.
  41194. *
  41195. * @return {ArrayCamera} The XR camera.
  41196. */
  41197. getCamera() {
  41198. return this._cameraXR;
  41199. }
  41200. /**
  41201. * Returns the environment blend mode from the current XR session.
  41202. *
  41203. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  41204. */
  41205. getEnvironmentBlendMode() {
  41206. if ( this._session !== null ) {
  41207. return this._session.environmentBlendMode;
  41208. }
  41209. }
  41210. /**
  41211. * Returns the current base layer.
  41212. *
  41213. * This is an `XRProjectionLayer` when the targeted XR device supports the
  41214. * WebXR Layers API, or an `XRWebGLLayer` otherwise.
  41215. *
  41216. * @return {?(XRWebGLLayer|XRProjectionLayer)} The XR base layer.
  41217. */
  41218. getBaseLayer() {
  41219. return this._glProjLayer !== null ? this._glProjLayer : this._glBaseLayer;
  41220. }
  41221. /**
  41222. * Returns the current XR binding.
  41223. *
  41224. * Creates a new binding if needed and the browser is
  41225. * capable of doing so.
  41226. *
  41227. * @return {?XRWebGLBinding} The XR binding. Returns `null` if one cannot be created.
  41228. */
  41229. getBinding() {
  41230. if ( this._glBinding === null && this._supportsGlBinding ) {
  41231. this._glBinding = new XRWebGLBinding( this._session, this._gl );
  41232. }
  41233. return this._glBinding;
  41234. }
  41235. /**
  41236. * Applies WebXR fixed foveation to the internal post-processing render target
  41237. * used by the first XR render pass before compositing into a projection layer.
  41238. *
  41239. * Browser-side `XRWebGLBinding.foveateBoundTexture()` failures are treated as
  41240. * non-fatal so they do not interrupt rendering.
  41241. *
  41242. * @param {RenderTarget} renderTarget - The internal render target.
  41243. */
  41244. foveateBoundTexture( renderTarget ) {
  41245. if ( renderTarget.isPostProcessingRenderTarget !== true ) return;
  41246. if ( this.isPresenting !== true ) return;
  41247. if ( this._glProjLayer === null ) return;
  41248. const backend = this._renderer.backend;
  41249. if ( backend === undefined || backend.isWebGLBackend !== true ) return;
  41250. if ( backend.state === null ) return;
  41251. const outputRenderTarget = this._renderer.getOutputRenderTarget();
  41252. if ( outputRenderTarget === null || outputRenderTarget.isXRRenderTarget !== true ) return;
  41253. const glBinding = this.getBinding();
  41254. if ( glBinding === null || typeof glBinding.foveateBoundTexture !== 'function' ) return;
  41255. this._renderer._textures.updateRenderTarget( renderTarget );
  41256. const { textureGPU, glTextureType } = backend.get( renderTarget.texture );
  41257. if ( textureGPU === undefined || glTextureType === undefined ) return;
  41258. if ( renderTarget._xrFoveationTextureGPU === textureGPU ) return;
  41259. renderTarget._xrFoveationTextureGPU = textureGPU;
  41260. backend.state.bindTexture( glTextureType, textureGPU );
  41261. try {
  41262. glBinding.foveateBoundTexture( glTextureType, this.getFoveation() );
  41263. } catch ( error ) {
  41264. warnOnce( `XRManager: Unable to foveate bound XR post-processing texture. ${error.name}: ${error.message}` );
  41265. } finally {
  41266. backend.state.unbindTexture();
  41267. }
  41268. }
  41269. /**
  41270. * Returns the current XR WebGPU binding.
  41271. *
  41272. * Creates a new binding if needed and the browser is
  41273. * capable of doing so.
  41274. *
  41275. * @return {?XRGPUBinding} The XR WebGPU binding. Returns `null` if one cannot be created.
  41276. */
  41277. getWebGPUBinding() {
  41278. if ( this._webgpuBinding === null && this._supportsWebGPUBinding ) {
  41279. this._webgpuBinding = new globalThis.XRGPUBinding( this._session, this._renderer.backend.device );
  41280. }
  41281. return this._webgpuBinding;
  41282. }
  41283. /**
  41284. * Returns whether the current XR session is using WebGPU.
  41285. *
  41286. * @private
  41287. * @return {boolean} Whether the current session uses the WebGPU backend and the `webgpu` session feature.
  41288. */
  41289. _isWebGPUSession() {
  41290. return this._renderer.backend.isWebGPUBackend === true &&
  41291. this._session !== null &&
  41292. this._session.enabledFeatures.includes( 'webgpu' );
  41293. }
  41294. /**
  41295. * Validates the current WebGPU XR session requirements.
  41296. *
  41297. * @private
  41298. */
  41299. _validateWebGPUSession() {
  41300. const renderer = this._renderer;
  41301. if ( renderer.backend.isWebGPUBackend !== true ) return;
  41302. if ( this._session.enabledFeatures.includes( 'webgpu' ) === false ) {
  41303. throw new Error( 'THREE.XRManager: WebGPU XR sessions require the "webgpu" session feature. Use VRButtonGPU/XRButton with "webgpu" enabled or use a WebGL backend.' );
  41304. }
  41305. if ( renderer.samples > 0 ) {
  41306. warnOnce( 'THREE.XRManager: WebGPU XR does not support MSAA yet. Disabling MSAA for this XR session.' );
  41307. if ( this._currentSamples === null ) this._currentSamples = renderer.samples;
  41308. renderer._samples = 0;
  41309. }
  41310. }
  41311. /**
  41312. * Initializes the WebGPU XR projection layer and render target.
  41313. *
  41314. * @private
  41315. * @async
  41316. * @param {XRSession} session - The XR session.
  41317. * @return {Promise<void>}
  41318. */
  41319. async _initWebGPUSession( session ) {
  41320. const webgpuBinding = this.getWebGPUBinding();
  41321. const glProjLayer = webgpuBinding.createProjectionLayer( {
  41322. colorFormat: webgpuBinding.getPreferredColorFormat(),
  41323. depthStencilFormat: 'depth24plus'
  41324. } );
  41325. this._glProjLayer = glProjLayer;
  41326. session.updateRenderState( { layers: [ glProjLayer ] } );
  41327. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  41328. this._xrRenderTarget = new RenderTarget( glProjLayer.textureWidth, glProjLayer.textureHeight, {
  41329. depth: 2,
  41330. minFilter: LinearFilter,
  41331. magFilter: LinearFilter,
  41332. depthBuffer: true,
  41333. multiview: false,
  41334. useArrayDepthTexture: true,
  41335. samples: 0
  41336. } );
  41337. this._xrRenderTarget.texture.isArrayTexture = true;
  41338. if ( this._useMultiviewIfPossible === true ) {
  41339. warnOnce( 'THREE.XRManager: WebGPU XR does not support multiview yet. Disabling multiview for this XR session.' );
  41340. }
  41341. this._useMultiview = false;
  41342. }
  41343. /**
  41344. * Releases WebGPU XR resources associated with the current session.
  41345. *
  41346. * @private
  41347. */
  41348. _disposeWebGPUSession() {
  41349. const renderer = this._renderer;
  41350. const xrRenderTarget = this._xrRenderTarget;
  41351. if ( xrRenderTarget === null || renderer.backend.isWebGPUBackend !== true ) return;
  41352. // XR textures are external (from XRGPUBinding), so clear cached state before disposal.
  41353. const backend = renderer.backend;
  41354. const texturesModule = renderer._textures;
  41355. const renderTargetData = backend.get ? backend.get( xrRenderTarget ) : null;
  41356. if ( renderTargetData ) {
  41357. renderTargetData.descriptors = undefined;
  41358. }
  41359. const deleteResource = ( resource ) => {
  41360. if ( resource === null || resource === undefined ) return;
  41361. if ( backend.delete ) backend.delete( resource );
  41362. if ( texturesModule.delete ) texturesModule.delete( resource );
  41363. };
  41364. for ( let i = 0; i < xrRenderTarget.textures.length; i ++ ) {
  41365. deleteResource( xrRenderTarget.textures[ i ] );
  41366. }
  41367. deleteResource( xrRenderTarget.depthTexture );
  41368. deleteResource( xrRenderTarget );
  41369. if ( renderer._renderContexts && renderer._renderContexts.dispose ) {
  41370. renderer._renderContexts.dispose();
  41371. }
  41372. xrRenderTarget.dispose();
  41373. }
  41374. /**
  41375. * Collects WebGPU XR sub-image data for the current frame.
  41376. *
  41377. * @private
  41378. * @param {Array<XRView>} views - The XR views for the current pose.
  41379. * @return {{colorTexture:?GPUTexture, viewDescriptors:Array<Object>, viewports:Array<XRViewport>}} The WebGPU XR view data.
  41380. */
  41381. _getWebGPUViewData( views ) {
  41382. const webgpuBinding = this.getWebGPUBinding();
  41383. const viewData = {
  41384. colorTexture: null,
  41385. viewDescriptors: [],
  41386. viewports: []
  41387. };
  41388. for ( let i = 0; i < views.length; i ++ ) {
  41389. const gpuSubImage = webgpuBinding.getViewSubImage( this._glProjLayer, views[ i ] );
  41390. if ( viewData.colorTexture === null ) {
  41391. viewData.colorTexture = gpuSubImage.colorTexture;
  41392. }
  41393. viewData.viewports.push( gpuSubImage.viewport );
  41394. if ( gpuSubImage.getViewDescriptor ) {
  41395. viewData.viewDescriptors.push( gpuSubImage.getViewDescriptor() );
  41396. }
  41397. }
  41398. return viewData;
  41399. }
  41400. /**
  41401. * Returns the current XR frame.
  41402. *
  41403. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  41404. */
  41405. getFrame() {
  41406. return this._xrFrame;
  41407. }
  41408. /**
  41409. * Returns `true` if the engine renders to a multiview target.
  41410. *
  41411. * @return {boolean} Whether the engine renders to a multiview render target or not.
  41412. */
  41413. useMultiview() {
  41414. return this._useMultiview;
  41415. }
  41416. /**
  41417. * This method can be used in XR applications to create a quadratic layer that presents a separate
  41418. * rendered scene.
  41419. *
  41420. * @param {number} width - The width of the layer plane in world units.
  41421. * @param {number} height - The height of the layer plane in world units.
  41422. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  41423. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  41424. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  41425. * @param {number} pixelheight - The height of the layer's render target in pixels.
  41426. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  41427. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  41428. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  41429. * @return {Mesh} A mesh representing the quadratic XR layer. This mesh should be added to the XR scene.
  41430. */
  41431. createQuadLayer( width, height, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  41432. const geometry = new PlaneGeometry( width, height );
  41433. const renderTarget = new XRRenderTarget(
  41434. pixelwidth,
  41435. pixelheight,
  41436. {
  41437. format: RGBAFormat,
  41438. type: UnsignedByteType,
  41439. depthTexture: new DepthTexture(
  41440. pixelwidth,
  41441. pixelheight,
  41442. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  41443. undefined,
  41444. undefined,
  41445. undefined,
  41446. undefined,
  41447. undefined,
  41448. undefined,
  41449. attributes.stencil ? DepthStencilFormat : DepthFormat
  41450. ),
  41451. stencilBuffer: attributes.stencil,
  41452. resolveDepthBuffer: false,
  41453. resolveStencilBuffer: false,
  41454. storeMultisampledDepthBuffer: false,
  41455. storeMultisampledStencilBuffer: false
  41456. } );
  41457. renderTarget._autoAllocateDepthBuffer = true;
  41458. const material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  41459. material.map = renderTarget.texture;
  41460. material.map.offset.y = 1;
  41461. material.map.repeat.y = -1;
  41462. const plane = new Mesh( geometry, material );
  41463. plane.position.copy( translation );
  41464. plane.quaternion.copy( quaternion );
  41465. const layer = {
  41466. type: 'quad',
  41467. width: width,
  41468. height: height,
  41469. translation: translation,
  41470. quaternion: quaternion,
  41471. pixelwidth: pixelwidth,
  41472. pixelheight: pixelheight,
  41473. plane: plane,
  41474. material: material,
  41475. rendercall: rendercall,
  41476. renderTarget: renderTarget };
  41477. this._layers.push( layer );
  41478. if ( this._session !== null ) {
  41479. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  41480. layer.plane.material.blending = CustomBlending;
  41481. layer.plane.material.blendEquation = AddEquation;
  41482. layer.plane.material.blendSrc = ZeroFactor;
  41483. layer.plane.material.blendDst = ZeroFactor;
  41484. layer.xrlayer = this._createXRLayer( layer );
  41485. const xrlayers = this._session.renderState.layers;
  41486. xrlayers.unshift( layer.xrlayer );
  41487. this._session.updateRenderState( { layers: xrlayers } );
  41488. } else {
  41489. renderTarget.isXRRenderTarget = false;
  41490. }
  41491. return plane;
  41492. }
  41493. /**
  41494. * This method can be used in XR applications to create a cylindrical layer that presents a separate
  41495. * rendered scene.
  41496. *
  41497. * @param {number} radius - The radius of the cylinder in world units.
  41498. * @param {number} centralAngle - The central angle of the cylinder in radians.
  41499. * @param {number} aspectratio - The aspect ratio.
  41500. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  41501. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  41502. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  41503. * @param {number} pixelheight - The height of the layer's render target in pixels.
  41504. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  41505. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  41506. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  41507. * @return {Mesh} A mesh representing the cylindrical XR layer. This mesh should be added to the XR scene.
  41508. */
  41509. createCylinderLayer( radius, centralAngle, aspectratio, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  41510. const geometry = new CylinderGeometry( radius, radius, radius * centralAngle / aspectratio, 64, 64, true, Math.PI - centralAngle / 2, centralAngle );
  41511. const renderTarget = new XRRenderTarget(
  41512. pixelwidth,
  41513. pixelheight,
  41514. {
  41515. format: RGBAFormat,
  41516. type: UnsignedByteType,
  41517. depthTexture: new DepthTexture(
  41518. pixelwidth,
  41519. pixelheight,
  41520. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  41521. undefined,
  41522. undefined,
  41523. undefined,
  41524. undefined,
  41525. undefined,
  41526. undefined,
  41527. attributes.stencil ? DepthStencilFormat : DepthFormat
  41528. ),
  41529. stencilBuffer: attributes.stencil,
  41530. resolveDepthBuffer: false,
  41531. resolveStencilBuffer: false,
  41532. storeMultisampledDepthBuffer: false,
  41533. storeMultisampledStencilBuffer: false
  41534. } );
  41535. renderTarget._autoAllocateDepthBuffer = true;
  41536. const material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  41537. material.map = renderTarget.texture;
  41538. material.map.offset.y = 1;
  41539. material.map.repeat.y = -1;
  41540. const plane = new Mesh( geometry, material );
  41541. plane.position.copy( translation );
  41542. plane.quaternion.copy( quaternion );
  41543. const layer = {
  41544. type: 'cylinder',
  41545. radius: radius,
  41546. centralAngle: centralAngle,
  41547. aspectratio: aspectratio,
  41548. translation: translation,
  41549. quaternion: quaternion,
  41550. pixelwidth: pixelwidth,
  41551. pixelheight: pixelheight,
  41552. plane: plane,
  41553. material: material,
  41554. rendercall: rendercall,
  41555. renderTarget: renderTarget };
  41556. this._layers.push( layer );
  41557. if ( this._session !== null ) {
  41558. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  41559. layer.plane.material.blending = CustomBlending;
  41560. layer.plane.material.blendEquation = AddEquation;
  41561. layer.plane.material.blendSrc = ZeroFactor;
  41562. layer.plane.material.blendDst = ZeroFactor;
  41563. layer.xrlayer = this._createXRLayer( layer );
  41564. const xrlayers = this._session.renderState.layers;
  41565. xrlayers.unshift( layer.xrlayer );
  41566. this._session.updateRenderState( { layers: xrlayers } );
  41567. } else {
  41568. renderTarget.isXRRenderTarget = false;
  41569. }
  41570. return plane;
  41571. }
  41572. /**
  41573. * Renders the XR layers that have been previously added to the scene.
  41574. *
  41575. * This method is usually called in your animation loop before rendering
  41576. * the actual scene via `renderer.render( scene, camera );`.
  41577. */
  41578. renderLayers( ) {
  41579. const translationObject = new Vector3();
  41580. const quaternionObject = new Quaternion();
  41581. const renderer = this._renderer;
  41582. const wasPresenting = this.isPresenting;
  41583. this.isPresenting = false;
  41584. const rendererSize = new Vector2();
  41585. renderer.getSize( rendererSize );
  41586. const currentRenderTarget = renderer.getRenderTarget();
  41587. for ( const layer of this._layers ) {
  41588. layer.renderTarget.isXRRenderTarget = this._session !== null;
  41589. layer.renderTarget._hasExternalTextures = layer.renderTarget.isXRRenderTarget;
  41590. const currentContextNode = renderer.contextNode;
  41591. let contextNode;
  41592. if ( layer.renderTarget.isXRRenderTarget && this._sessionUsesLayers ) {
  41593. layer.xrlayer.transform = new XRRigidTransform( layer.plane.getWorldPosition( translationObject ), layer.plane.getWorldQuaternion( quaternionObject ) );
  41594. const glSubImage = this._glBinding.getSubImage( layer.xrlayer, this._xrFrame );
  41595. renderer.backend.setXRRenderTargetTextures(
  41596. layer.renderTarget,
  41597. glSubImage.colorTexture,
  41598. undefined );
  41599. renderer._setXRLayerSize( layer.renderTarget.width, layer.renderTarget.height );
  41600. contextNode = _contextNodeLib.get( currentContextNode );
  41601. if ( contextNode === undefined ) {
  41602. // Apply ToneMapping and OutputColorSpace directly in the material shader
  41603. contextNode = currentContextNode.context( {
  41604. getOutput: ( outputNode ) => {
  41605. return renderOutput( outputNode, renderer.toneMapping, renderer.outputColorSpace );
  41606. }
  41607. } );
  41608. _contextNodeLib.set( currentContextNode, contextNode );
  41609. }
  41610. } else {
  41611. contextNode = currentContextNode;
  41612. }
  41613. renderer.contextNode = contextNode;
  41614. renderer.setRenderTarget( layer.renderTarget );
  41615. layer.rendercall();
  41616. renderer.contextNode = currentContextNode;
  41617. }
  41618. renderer.setRenderTarget( currentRenderTarget );
  41619. renderer._setXRLayerSize( rendererSize.x, rendererSize.y );
  41620. this.isPresenting = wasPresenting;
  41621. }
  41622. /**
  41623. * Returns the current XR session.
  41624. *
  41625. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  41626. */
  41627. getSession() {
  41628. return this._session;
  41629. }
  41630. /**
  41631. * After a XR session has been requested usually with one of the `*Button` modules, it
  41632. * is injected into the renderer with this method. This method triggers the start of
  41633. * the actual XR rendering.
  41634. *
  41635. * @async
  41636. * @param {XRSession} session - The XR session to set.
  41637. * @return {Promise} A Promise that resolves when the session has been set.
  41638. */
  41639. async setSession( session ) {
  41640. const renderer = this._renderer;
  41641. if ( renderer.initialized === false ) await renderer.init();
  41642. this._gl = renderer.getContext();
  41643. const gl = this._gl;
  41644. this._session = session;
  41645. if ( session !== null ) {
  41646. session.addEventListener( 'select', this._onSessionEvent );
  41647. session.addEventListener( 'selectstart', this._onSessionEvent );
  41648. session.addEventListener( 'selectend', this._onSessionEvent );
  41649. session.addEventListener( 'squeeze', this._onSessionEvent );
  41650. session.addEventListener( 'squeezestart', this._onSessionEvent );
  41651. session.addEventListener( 'squeezeend', this._onSessionEvent );
  41652. session.addEventListener( 'end', this._onSessionEnd );
  41653. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  41654. this._validateWebGPUSession();
  41655. this._currentPixelRatio = renderer.getPixelRatio();
  41656. renderer.getSize( this._currentSize );
  41657. this._currentAnimationContext = renderer._animation.getContext();
  41658. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  41659. renderer._animation.stop();
  41660. //
  41661. if ( this._isWebGPUSession() ) {
  41662. await this._initWebGPUSession( session );
  41663. } else if ( this._supportsLayers === true ) {
  41664. // default path using XRProjectionLayer
  41665. let depthFormat = null;
  41666. let depthType = null;
  41667. let glDepthFormat = null;
  41668. const attributes = gl.getContextAttributes();
  41669. await renderer.backend.makeXRCompatible();
  41670. this.setFoveation( this.getFoveation() );
  41671. if ( renderer.depth ) {
  41672. glDepthFormat = renderer.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  41673. depthFormat = renderer.stencil ? DepthStencilFormat : DepthFormat;
  41674. depthType = renderer.stencil ? UnsignedInt248Type : UnsignedIntType;
  41675. }
  41676. const projectionlayerInit = {
  41677. colorFormat: gl.RGBA8,
  41678. depthFormat: glDepthFormat,
  41679. scaleFactor: this._framebufferScaleFactor,
  41680. clearOnAccess: false
  41681. };
  41682. if ( this._useMultiviewIfPossible && renderer.hasFeature( 'OVR_multiview2' ) ) {
  41683. projectionlayerInit.textureType = 'texture-array';
  41684. this._useMultiview = true;
  41685. }
  41686. this._glBinding = this.getBinding();
  41687. const glProjLayer = this._glBinding.createProjectionLayer( projectionlayerInit );
  41688. const layersArray = [ glProjLayer ];
  41689. this._glProjLayer = glProjLayer;
  41690. renderer.setPixelRatio( 1 );
  41691. renderer._setXRLayerSize( glProjLayer.textureWidth, glProjLayer.textureHeight );
  41692. const depth = this._useMultiview ? 2 : 1;
  41693. const depthTexture = new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat, depth );
  41694. this._xrRenderTarget = new XRRenderTarget(
  41695. glProjLayer.textureWidth,
  41696. glProjLayer.textureHeight,
  41697. {
  41698. format: RGBAFormat,
  41699. type: UnsignedByteType,
  41700. colorSpace: renderer.outputColorSpace,
  41701. depthTexture: depthTexture,
  41702. stencilBuffer: renderer.stencil,
  41703. samples: attributes.antialias ? 4 : 0,
  41704. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  41705. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false ),
  41706. storeMultisampledColorBuffer: false,
  41707. storeMultisampledDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  41708. storeMultisampledStencilBuffer: ( glProjLayer.ignoreDepthValues === false ),
  41709. depth: this._useMultiview ? 2 : 1,
  41710. multiview: this._useMultiview
  41711. } );
  41712. this._xrRenderTarget._hasExternalTextures = true;
  41713. this._xrRenderTarget.depth = this._useMultiview ? 2 : 1;
  41714. this._sessionUsesLayers = session.enabledFeatures.includes( 'layers' );
  41715. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  41716. if ( this._sessionUsesLayers ) {
  41717. // switch layers to native
  41718. for ( const layer of this._layers ) {
  41719. // change material so it "punches" out a hole to show the XR Layer.
  41720. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: layer.type === 'cylinder' ? BackSide : FrontSide } );
  41721. layer.plane.material.blending = CustomBlending;
  41722. layer.plane.material.blendEquation = AddEquation;
  41723. layer.plane.material.blendSrc = ZeroFactor;
  41724. layer.plane.material.blendDst = ZeroFactor;
  41725. layer.xrlayer = this._createXRLayer( layer );
  41726. layersArray.unshift( layer.xrlayer );
  41727. }
  41728. }
  41729. session.updateRenderState( { layers: layersArray } );
  41730. } else {
  41731. // fallback to XRWebGLLayer
  41732. await renderer.backend.makeXRCompatible();
  41733. this.setFoveation( this.getFoveation() );
  41734. const layerInit = {
  41735. antialias: renderer.currentSamples > 0,
  41736. alpha: true,
  41737. depth: renderer.depth,
  41738. stencil: renderer.stencil,
  41739. framebufferScaleFactor: this.getFramebufferScaleFactor()
  41740. };
  41741. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  41742. this._glBaseLayer = glBaseLayer;
  41743. session.updateRenderState( { baseLayer: glBaseLayer } );
  41744. renderer.setPixelRatio( 1 );
  41745. renderer._setXRLayerSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight );
  41746. this._xrRenderTarget = new XRRenderTarget(
  41747. glBaseLayer.framebufferWidth,
  41748. glBaseLayer.framebufferHeight,
  41749. {
  41750. format: RGBAFormat,
  41751. type: UnsignedByteType,
  41752. colorSpace: renderer.outputColorSpace,
  41753. stencilBuffer: renderer.stencil,
  41754. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  41755. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  41756. storeMultisampledDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  41757. storeMultisampledStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  41758. }
  41759. );
  41760. this._xrRenderTarget._isOpaqueFramebuffer = true;
  41761. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  41762. }
  41763. //
  41764. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  41765. renderer._animation.setContext( session );
  41766. renderer._animation.start();
  41767. this.isPresenting = true;
  41768. this.dispatchEvent( { type: 'sessionstart' } );
  41769. }
  41770. }
  41771. /**
  41772. * This method is called by the renderer per frame and updates the XR camera
  41773. * and it sub cameras based on the given camera. The given camera is the "user"
  41774. * camera created on application level and used for non-XR rendering.
  41775. *
  41776. * @param {PerspectiveCamera} camera - The camera.
  41777. */
  41778. updateCamera( camera ) {
  41779. const session = this._session;
  41780. if ( session === null ) return;
  41781. const depthNear = camera.near;
  41782. const depthFar = camera.far;
  41783. const cameraXR = this._cameraXR;
  41784. const cameraL = this._cameraL;
  41785. const cameraR = this._cameraR;
  41786. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  41787. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  41788. cameraXR.isMultiViewCamera = this._useMultiview;
  41789. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  41790. // Note that the new renderState won't apply until the next frame. See #18320
  41791. session.updateRenderState( {
  41792. depthNear: cameraXR.near,
  41793. depthFar: cameraXR.far
  41794. } );
  41795. this._currentDepthNear = cameraXR.near;
  41796. this._currentDepthFar = cameraXR.far;
  41797. }
  41798. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  41799. cameraXR.layers.mask = camera.layers.mask | 0b110;
  41800. cameraL.layers.mask = cameraXR.layers.mask & -5;
  41801. cameraR.layers.mask = cameraXR.layers.mask & -3;
  41802. const parent = camera.parent;
  41803. const cameras = cameraXR.cameras;
  41804. updateCamera( cameraXR, parent );
  41805. for ( let i = 0; i < cameras.length; i ++ ) {
  41806. updateCamera( cameras[ i ], parent );
  41807. }
  41808. // update projection matrix for proper view frustum culling
  41809. if ( cameras.length === 2 ) {
  41810. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  41811. } else {
  41812. // assume single camera setup (AR)
  41813. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  41814. }
  41815. // update user camera and its children
  41816. updateUserCamera( camera, cameraXR, parent );
  41817. }
  41818. /**
  41819. * Returns a WebXR controller for the given controller index.
  41820. *
  41821. * @private
  41822. * @param {number} index - The controller index.
  41823. * @return {WebXRController} The XR controller.
  41824. */
  41825. _getController( index ) {
  41826. let controller = this._controllers[ index ];
  41827. if ( controller === undefined ) {
  41828. controller = new WebXRController();
  41829. this._controllers[ index ] = controller;
  41830. }
  41831. return controller;
  41832. }
  41833. }
  41834. /**
  41835. * Assumes 2 cameras that are parallel and share an X-axis, and that
  41836. * the cameras' projection and world matrices have already been set.
  41837. * And that near and far planes are identical for both cameras.
  41838. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  41839. *
  41840. * @param {ArrayCamera} camera - The camera to update.
  41841. * @param {PerspectiveCamera} cameraL - The left camera.
  41842. * @param {PerspectiveCamera} cameraR - The right camera.
  41843. */
  41844. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  41845. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  41846. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  41847. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  41848. const projL = cameraL.projectionMatrix.elements;
  41849. const projR = cameraR.projectionMatrix.elements;
  41850. // VR systems will have identical far and near planes, and
  41851. // most likely identical top and bottom frustum extents.
  41852. // Use the left camera for these values.
  41853. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  41854. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  41855. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  41856. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  41857. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  41858. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  41859. const left = near * leftFov;
  41860. const right = near * rightFov;
  41861. // Calculate the new camera's position offset from the
  41862. // left camera. xOffset should be roughly half `ipd`.
  41863. const zOffset = ipd / ( - leftFov + rightFov );
  41864. const xOffset = zOffset * - leftFov;
  41865. // TODO: Better way to apply this offset?
  41866. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  41867. camera.translateX( xOffset );
  41868. camera.translateZ( zOffset );
  41869. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  41870. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  41871. // Check if the projection uses an infinite far plane.
  41872. if ( projL[ 10 ] === -1 ) {
  41873. // Use the projection matrix from the left eye.
  41874. // The camera offset is sufficient to include the view volumes
  41875. // of both eyes (assuming symmetric projections).
  41876. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  41877. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  41878. } else {
  41879. // Find the union of the frustum values of the cameras and scale
  41880. // the values so that the near plane's position does not change in world space,
  41881. // although must now be relative to the new union camera.
  41882. const near2 = near + zOffset;
  41883. const far2 = far + zOffset;
  41884. const left2 = left - xOffset;
  41885. const right2 = right + ( ipd - xOffset );
  41886. const top2 = topFov * far / far2 * near2;
  41887. const bottom2 = bottomFov * far / far2 * near2;
  41888. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  41889. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  41890. }
  41891. }
  41892. /**
  41893. * Updates the world matrices for the given camera based on the parent 3D object.
  41894. *
  41895. * @inner
  41896. * @param {Camera} camera - The camera to update.
  41897. * @param {Object3D} parent - The parent 3D object.
  41898. */
  41899. function updateCamera( camera, parent ) {
  41900. if ( parent === null ) {
  41901. camera.matrixWorld.copy( camera.matrix );
  41902. } else {
  41903. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  41904. }
  41905. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  41906. }
  41907. /**
  41908. * Updates the given camera with the transformation of the XR camera and parent object.
  41909. *
  41910. * @inner
  41911. * @param {Camera} camera - The camera to update.
  41912. * @param {ArrayCamera} cameraXR - The XR camera.
  41913. * @param {Object3D} parent - The parent 3D object.
  41914. */
  41915. function updateUserCamera( camera, cameraXR, parent ) {
  41916. if ( parent === null ) {
  41917. camera.matrix.copy( cameraXR.matrixWorld );
  41918. } else {
  41919. camera.matrix.copy( parent.matrixWorld );
  41920. camera.matrix.invert();
  41921. camera.matrix.multiply( cameraXR.matrixWorld );
  41922. }
  41923. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  41924. camera.updateMatrixWorld( true );
  41925. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  41926. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  41927. if ( camera.isPerspectiveCamera ) {
  41928. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  41929. camera.zoom = 1;
  41930. }
  41931. }
  41932. function onSessionEvent( event ) {
  41933. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  41934. if ( controllerIndex === -1 ) {
  41935. return;
  41936. }
  41937. const controller = this._controllers[ controllerIndex ];
  41938. if ( controller !== undefined ) {
  41939. const referenceSpace = this.getReferenceSpace();
  41940. controller.update( event.inputSource, event.frame, referenceSpace );
  41941. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  41942. }
  41943. }
  41944. function onSessionEnd() {
  41945. const session = this._session;
  41946. const renderer = this._renderer;
  41947. session.removeEventListener( 'select', this._onSessionEvent );
  41948. session.removeEventListener( 'selectstart', this._onSessionEvent );
  41949. session.removeEventListener( 'selectend', this._onSessionEvent );
  41950. session.removeEventListener( 'squeeze', this._onSessionEvent );
  41951. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  41952. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  41953. session.removeEventListener( 'end', this._onSessionEnd );
  41954. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  41955. for ( let i = 0; i < this._controllers.length; i ++ ) {
  41956. const inputSource = this._controllerInputSources[ i ];
  41957. if ( inputSource === null ) continue;
  41958. this._controllerInputSources[ i ] = null;
  41959. this._controllers[ i ].disconnect( inputSource );
  41960. }
  41961. this._currentDepthNear = null;
  41962. this._currentDepthFar = null;
  41963. if ( this._currentSamples !== null ) {
  41964. renderer._samples = this._currentSamples;
  41965. this._currentSamples = null;
  41966. }
  41967. // restore framebuffer/rendering state
  41968. renderer._resetXRState();
  41969. this._disposeWebGPUSession();
  41970. this._session = null;
  41971. this._xrRenderTarget = null;
  41972. this._glBinding = null;
  41973. this._webgpuBinding = null;
  41974. this._glBaseLayer = null;
  41975. this._glProjLayer = null;
  41976. // switch layers back to emulated
  41977. if ( this._sessionUsesLayers === true ) {
  41978. for ( const layer of this._layers ) {
  41979. // Recreate layer render target to reset state
  41980. layer.renderTarget = new XRRenderTarget(
  41981. layer.pixelwidth,
  41982. layer.pixelheight,
  41983. {
  41984. format: RGBAFormat,
  41985. type: UnsignedByteType,
  41986. depthTexture: new DepthTexture(
  41987. layer.pixelwidth,
  41988. layer.pixelheight,
  41989. layer.stencilBuffer ? UnsignedInt248Type : UnsignedIntType,
  41990. undefined,
  41991. undefined,
  41992. undefined,
  41993. undefined,
  41994. undefined,
  41995. undefined,
  41996. layer.stencilBuffer ? DepthStencilFormat : DepthFormat
  41997. ),
  41998. stencilBuffer: layer.stencilBuffer,
  41999. resolveDepthBuffer: false,
  42000. resolveStencilBuffer: false,
  42001. storeMultisampledDepthBuffer: false,
  42002. storeMultisampledStencilBuffer: false
  42003. } );
  42004. layer.renderTarget.isXRRenderTarget = false;
  42005. layer.plane.material = layer.material;
  42006. layer.material.map = layer.renderTarget.texture;
  42007. layer.material.map.offset.y = 1;
  42008. layer.material.map.repeat.y = -1;
  42009. delete layer.xrlayer;
  42010. }
  42011. }
  42012. //
  42013. this.isPresenting = false;
  42014. this._useMultiview = false;
  42015. renderer._animation.stop();
  42016. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  42017. renderer._animation.setContext( this._currentAnimationContext );
  42018. renderer._animation.start();
  42019. renderer.setPixelRatio( this._currentPixelRatio );
  42020. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  42021. this.dispatchEvent( { type: 'sessionend' } );
  42022. }
  42023. function onInputSourcesChange( event ) {
  42024. const controllers = this._controllers;
  42025. const controllerInputSources = this._controllerInputSources;
  42026. // Notify disconnected
  42027. for ( let i = 0; i < event.removed.length; i ++ ) {
  42028. const inputSource = event.removed[ i ];
  42029. const index = controllerInputSources.indexOf( inputSource );
  42030. if ( index >= 0 ) {
  42031. controllerInputSources[ index ] = null;
  42032. controllers[ index ].disconnect( inputSource );
  42033. }
  42034. }
  42035. // Notify connected
  42036. for ( let i = 0; i < event.added.length; i ++ ) {
  42037. const inputSource = event.added[ i ];
  42038. let controllerIndex = controllerInputSources.indexOf( inputSource );
  42039. if ( controllerIndex === -1 ) {
  42040. // Assign input source a controller that currently has no input source
  42041. for ( let i = 0; i < controllers.length; i ++ ) {
  42042. if ( i >= controllerInputSources.length ) {
  42043. controllerInputSources.push( inputSource );
  42044. controllerIndex = i;
  42045. break;
  42046. } else if ( controllerInputSources[ i ] === null ) {
  42047. controllerInputSources[ i ] = inputSource;
  42048. controllerIndex = i;
  42049. break;
  42050. }
  42051. }
  42052. // If all controllers do currently receive input we ignore new ones
  42053. if ( controllerIndex === -1 ) break;
  42054. }
  42055. const controller = controllers[ controllerIndex ];
  42056. if ( controller ) {
  42057. controller.connect( inputSource );
  42058. }
  42059. }
  42060. }
  42061. // Creation method for native WebXR layers
  42062. function createXRLayer( layer ) {
  42063. if ( layer.type === 'quad' ) {
  42064. return this._glBinding.createQuadLayer( {
  42065. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  42066. width: layer.width / 2,
  42067. height: layer.height / 2,
  42068. space: this._referenceSpace,
  42069. viewPixelWidth: layer.pixelwidth,
  42070. viewPixelHeight: layer.pixelheight,
  42071. clearOnAccess: false
  42072. } );
  42073. } else {
  42074. return this._glBinding.createCylinderLayer( {
  42075. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  42076. radius: layer.radius,
  42077. centralAngle: layer.centralAngle,
  42078. aspectRatio: layer.aspectRatio,
  42079. space: this._referenceSpace,
  42080. viewPixelWidth: layer.pixelwidth,
  42081. viewPixelHeight: layer.pixelheight,
  42082. clearOnAccess: false
  42083. } );
  42084. }
  42085. }
  42086. // Animation Loop
  42087. function onAnimationFrame( time, frame ) {
  42088. if ( frame === undefined ) return;
  42089. const cameraXR = this._cameraXR;
  42090. const renderer = this._renderer;
  42091. const backend = renderer.backend;
  42092. const glBaseLayer = this._glBaseLayer;
  42093. const referenceSpace = this.getReferenceSpace();
  42094. const pose = frame.getViewerPose( referenceSpace );
  42095. this._xrFrame = frame;
  42096. if ( pose !== null ) {
  42097. const views = pose.views;
  42098. const webgpuViewData = this._isWebGPUSession() ? this._getWebGPUViewData( views ) : null;
  42099. if ( this._glBaseLayer !== null && webgpuViewData === null ) {
  42100. backend.setXRTarget( glBaseLayer.framebuffer );
  42101. }
  42102. let cameraXRNeedsUpdate = false;
  42103. // check if it's necessary to rebuild cameraXR's camera list
  42104. if ( views.length !== cameraXR.cameras.length ) {
  42105. cameraXR.cameras.length = 0;
  42106. cameraXRNeedsUpdate = true;
  42107. }
  42108. for ( let i = 0; i < views.length; i ++ ) {
  42109. const view = views[ i ];
  42110. let viewport;
  42111. if ( webgpuViewData !== null ) {
  42112. viewport = webgpuViewData.viewports[ i ];
  42113. } else if ( this._supportsLayers === true ) {
  42114. // WebGL path: Use XRWebGLBinding
  42115. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  42116. viewport = glSubImage.viewport;
  42117. // For side-by-side projection, we only produce a single texture for both eyes.
  42118. if ( i === 0 ) {
  42119. backend.setXRRenderTargetTextures(
  42120. this._xrRenderTarget,
  42121. glSubImage.colorTexture,
  42122. ( this._glProjLayer.ignoreDepthValues && ! this._useMultiview ) ? undefined : glSubImage.depthStencilTexture
  42123. );
  42124. }
  42125. } else {
  42126. viewport = glBaseLayer.getViewport( view );
  42127. }
  42128. let camera = this._cameras[ i ];
  42129. if ( camera === undefined ) {
  42130. camera = new PerspectiveCamera();
  42131. camera.layers.enable( i );
  42132. camera.viewport = new Vector4();
  42133. camera.matrixWorldAutoUpdate = false;
  42134. this._cameras[ i ] = camera;
  42135. }
  42136. camera.matrix.fromArray( view.transform.matrix );
  42137. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  42138. camera.projectionMatrix.fromArray( view.projectionMatrix );
  42139. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  42140. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  42141. if ( i === 0 ) {
  42142. cameraXR.matrix.copy( camera.matrix );
  42143. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  42144. }
  42145. if ( cameraXRNeedsUpdate === true ) {
  42146. cameraXR.cameras.push( camera );
  42147. }
  42148. }
  42149. if ( webgpuViewData !== null && webgpuViewData.colorTexture !== null ) {
  42150. backend.setXRRenderTargetTextures(
  42151. this._xrRenderTarget,
  42152. webgpuViewData.colorTexture,
  42153. webgpuViewData.viewDescriptors
  42154. );
  42155. }
  42156. renderer.setOutputRenderTarget( this._xrRenderTarget );
  42157. const frameBufferTarget = renderer._getFrameBufferTarget();
  42158. renderer.xr.foveateBoundTexture( frameBufferTarget );
  42159. }
  42160. //
  42161. for ( let i = 0; i < this._controllers.length; i ++ ) {
  42162. const inputSource = this._controllerInputSources[ i ];
  42163. const controller = this._controllers[ i ];
  42164. if ( inputSource !== null && controller !== undefined ) {
  42165. controller.update( inputSource, frame, referenceSpace );
  42166. }
  42167. }
  42168. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  42169. if ( frame.detectedPlanes ) {
  42170. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  42171. }
  42172. this._xrFrame = null;
  42173. }
  42174. /**
  42175. * CanvasTarget is a class that represents the final output destination of the renderer.
  42176. *
  42177. * @augments EventDispatcher
  42178. */
  42179. class CanvasTarget extends EventDispatcher {
  42180. /**
  42181. * Constructs a new CanvasTarget.
  42182. *
  42183. * @param {HTMLCanvasElement|OffscreenCanvas} domElement - The canvas element to render to.
  42184. */
  42185. constructor( domElement ) {
  42186. super();
  42187. /**
  42188. * A reference to the canvas element the renderer is drawing to.
  42189. * This value of this property will automatically be created by
  42190. * the renderer.
  42191. *
  42192. * @type {HTMLCanvasElement|OffscreenCanvas}
  42193. */
  42194. this.domElement = domElement;
  42195. /**
  42196. * The renderer's pixel ratio.
  42197. *
  42198. * @private
  42199. * @type {number}
  42200. * @default 1
  42201. */
  42202. this._pixelRatio = 1;
  42203. /**
  42204. * The width of the renderer's default framebuffer in logical pixel unit.
  42205. *
  42206. * @private
  42207. * @type {number}
  42208. */
  42209. this._width = this.domElement.width;
  42210. /**
  42211. * The height of the renderer's default framebuffer in logical pixel unit.
  42212. *
  42213. * @private
  42214. * @type {number}
  42215. */
  42216. this._height = this.domElement.height;
  42217. /**
  42218. * The viewport of the renderer in logical pixel unit.
  42219. *
  42220. * @private
  42221. * @type {Vector4}
  42222. */
  42223. this._viewport = new Vector4( 0, 0, this._width, this._height );
  42224. /**
  42225. * The scissor rectangle of the renderer in logical pixel unit.
  42226. *
  42227. * @private
  42228. * @type {Vector4}
  42229. */
  42230. this._scissor = new Vector4( 0, 0, this._width, this._height );
  42231. /**
  42232. * Whether the scissor test should be enabled or not.
  42233. *
  42234. * @private
  42235. * @type {boolean}
  42236. */
  42237. this._scissorTest = false;
  42238. /**
  42239. * The color texture of the default framebuffer.
  42240. *
  42241. * @type {FramebufferTexture}
  42242. */
  42243. this.colorTexture = new FramebufferTexture();
  42244. /**
  42245. * The depth texture of the default framebuffer.
  42246. *
  42247. * @type {DepthTexture}
  42248. */
  42249. this.depthTexture = new DepthTexture();
  42250. }
  42251. /**
  42252. * Returns the pixel ratio.
  42253. *
  42254. * @return {number} The pixel ratio.
  42255. */
  42256. getPixelRatio() {
  42257. return this._pixelRatio;
  42258. }
  42259. /**
  42260. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  42261. *
  42262. * @param {Vector2} target - The method writes the result in this target object.
  42263. * @return {Vector2} The drawing buffer size.
  42264. */
  42265. getDrawingBufferSize( target ) {
  42266. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  42267. }
  42268. /**
  42269. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  42270. *
  42271. * @param {Vector2} target - The method writes the result in this target object.
  42272. * @return {Vector2} The renderer's size in logical pixels.
  42273. */
  42274. getSize( target ) {
  42275. return target.set( this._width, this._height );
  42276. }
  42277. /**
  42278. * Sets the given pixel ratio and resizes the canvas if necessary.
  42279. *
  42280. * @param {number} [value=1] - The pixel ratio.
  42281. */
  42282. setPixelRatio( value = 1 ) {
  42283. if ( this._pixelRatio === value ) return;
  42284. this._pixelRatio = value;
  42285. this.setSize( this._width, this._height, false );
  42286. }
  42287. /**
  42288. * This method allows to define the drawing buffer size by specifying
  42289. * width, height and pixel ratio all at once. The size of the drawing
  42290. * buffer is computed with this formula:
  42291. * ```js
  42292. * size.x = width * pixelRatio;
  42293. * size.y = height * pixelRatio;
  42294. * ```
  42295. *
  42296. * @param {number} width - The width in logical pixels.
  42297. * @param {number} height - The height in logical pixels.
  42298. * @param {number} pixelRatio - The pixel ratio.
  42299. */
  42300. setDrawingBufferSize( width, height, pixelRatio ) {
  42301. // Renderer can't be resized while presenting in XR.
  42302. if ( this.xr && this.xr.isPresenting ) return;
  42303. this._width = width;
  42304. this._height = height;
  42305. this._pixelRatio = pixelRatio;
  42306. this.domElement.width = Math.floor( width * pixelRatio );
  42307. this.domElement.height = Math.floor( height * pixelRatio );
  42308. this.setViewport( 0, 0, width, height );
  42309. this._dispatchResize();
  42310. }
  42311. /**
  42312. * Sets the size of the renderer.
  42313. *
  42314. * @param {number} width - The width in logical pixels.
  42315. * @param {number} height - The height in logical pixels.
  42316. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  42317. */
  42318. setSize( width, height, updateStyle = true ) {
  42319. // Renderer can't be resized while presenting in XR.
  42320. if ( this.xr && this.xr.isPresenting ) return;
  42321. this._width = width;
  42322. this._height = height;
  42323. this.domElement.width = Math.floor( width * this._pixelRatio );
  42324. this.domElement.height = Math.floor( height * this._pixelRatio );
  42325. if ( updateStyle === true ) {
  42326. this.domElement.style.width = width + 'px';
  42327. this.domElement.style.height = height + 'px';
  42328. }
  42329. this.setViewport( 0, 0, width, height );
  42330. this._dispatchResize();
  42331. }
  42332. /**
  42333. * Returns the scissor rectangle.
  42334. *
  42335. * @param {Vector4} target - The method writes the result in this target object.
  42336. * @return {Vector4} The scissor rectangle.
  42337. */
  42338. getScissor( target ) {
  42339. const scissor = this._scissor;
  42340. target.x = scissor.x;
  42341. target.y = scissor.y;
  42342. target.width = scissor.width;
  42343. target.height = scissor.height;
  42344. return target;
  42345. }
  42346. /**
  42347. * Defines the scissor rectangle.
  42348. *
  42349. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  42350. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  42351. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  42352. * @param {number} width - The width of the scissor box in logical pixel unit.
  42353. * @param {number} height - The height of the scissor box in logical pixel unit.
  42354. */
  42355. setScissor( x, y, width, height ) {
  42356. const scissor = this._scissor;
  42357. if ( x.isVector4 ) {
  42358. scissor.copy( x );
  42359. } else {
  42360. scissor.set( x, y, width, height );
  42361. }
  42362. }
  42363. /**
  42364. * Returns the scissor test value.
  42365. *
  42366. * @return {boolean} Whether the scissor test should be enabled or not.
  42367. */
  42368. getScissorTest() {
  42369. return this._scissorTest;
  42370. }
  42371. /**
  42372. * Defines the scissor test.
  42373. *
  42374. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  42375. */
  42376. setScissorTest( boolean ) {
  42377. this._scissorTest = boolean;
  42378. }
  42379. /**
  42380. * Returns the viewport definition.
  42381. *
  42382. * @param {Vector4} target - The method writes the result in this target object.
  42383. * @return {Vector4} The viewport definition.
  42384. */
  42385. getViewport( target ) {
  42386. return target.copy( this._viewport );
  42387. }
  42388. /**
  42389. * Defines the viewport.
  42390. *
  42391. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  42392. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  42393. * @param {number} width - The width of the viewport in logical pixel unit.
  42394. * @param {number} height - The height of the viewport in logical pixel unit.
  42395. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  42396. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  42397. */
  42398. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  42399. const viewport = this._viewport;
  42400. if ( x.isVector4 ) {
  42401. viewport.copy( x );
  42402. } else {
  42403. viewport.set( x, y, width, height );
  42404. }
  42405. viewport.minDepth = minDepth;
  42406. viewport.maxDepth = maxDepth;
  42407. }
  42408. /**
  42409. * Dispatches the resize event.
  42410. *
  42411. * @private
  42412. */
  42413. _dispatchResize() {
  42414. this.dispatchEvent( { type: 'resize' } );
  42415. }
  42416. /**
  42417. * Frees the GPU-related resources allocated by this instance. Call this
  42418. * method whenever this instance is no longer used in your app.
  42419. *
  42420. * @fires RenderTarget#dispose
  42421. */
  42422. dispose() {
  42423. this.dispatchEvent( { type: 'dispose' } );
  42424. }
  42425. }
  42426. const _scene = /*@__PURE__*/ new Scene();
  42427. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  42428. const _screen = /*@__PURE__*/ new Vector4();
  42429. const _frustum = /*@__PURE__*/ new Frustum();
  42430. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  42431. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  42432. const _vector4 = /*@__PURE__*/ new Vector4();
  42433. const _shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  42434. /**
  42435. * Base class for renderers.
  42436. */
  42437. class Renderer {
  42438. /**
  42439. * Renderer options.
  42440. *
  42441. * @typedef {Object} Renderer~Options
  42442. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  42443. * @property {boolean} [reversedDepthBuffer=false] - Whether reversed depth buffer is enabled or not.
  42444. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  42445. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  42446. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  42447. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  42448. * @property {number} [samples=0] - When `antialias` is `true`, `4` samples are used by default. This parameter can set to any other integer value than 0
  42449. * to overwrite the default.
  42450. * @property {?Function} [getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  42451. * @property {number} [outputBufferType=HalfFloatType] - Defines the type of output buffers. The default `HalfFloatType` is recommend for best
  42452. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  42453. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  42454. */
  42455. /**
  42456. * Constructs a new renderer.
  42457. *
  42458. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  42459. * @param {Renderer~Options} [parameters] - The configuration parameter.
  42460. */
  42461. constructor( backend, parameters = {} ) {
  42462. /**
  42463. * This flag can be used for type testing.
  42464. *
  42465. * @type {boolean}
  42466. * @readonly
  42467. * @default true
  42468. */
  42469. this.isRenderer = true;
  42470. //
  42471. const {
  42472. logarithmicDepthBuffer = false,
  42473. reversedDepthBuffer = false,
  42474. alpha = true,
  42475. depth = true,
  42476. stencil = false,
  42477. antialias = false,
  42478. samples = 0,
  42479. getFallback = null,
  42480. outputBufferType = HalfFloatType,
  42481. multiview = false
  42482. } = parameters;
  42483. /**
  42484. * A reference to the current backend.
  42485. *
  42486. * @type {Backend}
  42487. */
  42488. this.backend = backend;
  42489. /**
  42490. * Whether the renderer should automatically clear the current rendering target
  42491. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  42492. * or the current bound render target (custom framebuffer).
  42493. *
  42494. * @type {boolean}
  42495. * @default true
  42496. */
  42497. this.autoClear = true;
  42498. /**
  42499. * When `autoClear` is set to `true`, this property defines whether the renderer
  42500. * should clear the color buffer.
  42501. *
  42502. * @type {boolean}
  42503. * @default true
  42504. */
  42505. this.autoClearColor = true;
  42506. /**
  42507. * When `autoClear` is set to `true`, this property defines whether the renderer
  42508. * should clear the depth buffer.
  42509. *
  42510. * @type {boolean}
  42511. * @default true
  42512. */
  42513. this.autoClearDepth = true;
  42514. /**
  42515. * When `autoClear` is set to `true`, this property defines whether the renderer
  42516. * should clear the stencil buffer.
  42517. *
  42518. * @type {boolean}
  42519. * @default true
  42520. */
  42521. this.autoClearStencil = true;
  42522. /**
  42523. * Whether the default framebuffer should be transparent or opaque.
  42524. *
  42525. * @type {boolean}
  42526. * @default true
  42527. */
  42528. this.alpha = alpha;
  42529. /**
  42530. * Whether logarithmic depth buffer is enabled or not.
  42531. *
  42532. * @type {boolean}
  42533. * @default false
  42534. * @readonly
  42535. */
  42536. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  42537. /**
  42538. * Whether reversed depth buffer is enabled or not.
  42539. *
  42540. * @type {boolean}
  42541. * @default false
  42542. * @readonly
  42543. */
  42544. this.reversedDepthBuffer = reversedDepthBuffer;
  42545. /**
  42546. * Defines the output color space of the renderer.
  42547. *
  42548. * @type {string}
  42549. * @default SRGBColorSpace
  42550. */
  42551. this.outputColorSpace = SRGBColorSpace;
  42552. /**
  42553. * Defines the tone mapping of the renderer.
  42554. *
  42555. * @type {number}
  42556. * @default NoToneMapping
  42557. */
  42558. this.toneMapping = NoToneMapping;
  42559. /**
  42560. * Defines the tone mapping exposure.
  42561. *
  42562. * @type {number}
  42563. * @default 1
  42564. */
  42565. this.toneMappingExposure = 1.0;
  42566. /**
  42567. * Whether the renderer should sort its render lists or not.
  42568. *
  42569. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  42570. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  42571. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  42572. * e.g. manually determining each object's rendering order.
  42573. *
  42574. * @type {boolean}
  42575. * @default true
  42576. */
  42577. this.sortObjects = true;
  42578. /**
  42579. * Whether the default framebuffer should have a depth buffer or not.
  42580. *
  42581. * @type {boolean}
  42582. * @default true
  42583. */
  42584. this.depth = depth;
  42585. /**
  42586. * Whether the default framebuffer should have a stencil buffer or not.
  42587. *
  42588. * @type {boolean}
  42589. * @default false
  42590. */
  42591. this.stencil = stencil;
  42592. /**
  42593. * Holds a series of statistical information about the GPU memory
  42594. * and the rendering process. Useful for debugging and monitoring.
  42595. *
  42596. * @type {Info}
  42597. */
  42598. this.info = new Info();
  42599. /**
  42600. * A global context node that stores override nodes for specific transformations or calculations.
  42601. * These nodes can be used to replace default behavior in the rendering pipeline.
  42602. *
  42603. * @type {ContextNode}
  42604. * @property {Object} value - The context value object.
  42605. */
  42606. this.contextNode = context();
  42607. /**
  42608. * The node library defines how certain library objects like materials, lights
  42609. * or tone mapping functions are mapped to node types. This is required since
  42610. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  42611. * be part of the scene graph, they are internally represented as nodes for
  42612. * further processing.
  42613. *
  42614. * @type {NodeLibrary}
  42615. */
  42616. this.library = new NodeLibrary();
  42617. /**
  42618. * A map-like data structure for managing lights.
  42619. *
  42620. * @type {Lighting}
  42621. */
  42622. this.lighting = new Lighting();
  42623. // internals
  42624. /**
  42625. * The number of MSAA samples.
  42626. *
  42627. * @private
  42628. * @type {number}
  42629. * @default 0
  42630. */
  42631. this._samples = samples || ( antialias === true ? 4 : 0 );
  42632. /**
  42633. * OnCanvasTargetResize callback function.
  42634. *
  42635. * @private
  42636. * @type {Function}
  42637. */
  42638. this._onCanvasTargetResize = this._onCanvasTargetResize.bind( this );
  42639. /**
  42640. * The canvas target for rendering.
  42641. *
  42642. * @private
  42643. * @type {CanvasTarget}
  42644. */
  42645. this._canvasTarget = new CanvasTarget( backend.getDomElement() );
  42646. this._canvasTarget.addEventListener( 'resize', this._onCanvasTargetResize );
  42647. this._canvasTarget.isDefaultCanvasTarget = true;
  42648. /**
  42649. * The inspector provides information about the internal renderer state.
  42650. *
  42651. * @private
  42652. * @type {InspectorBase}
  42653. */
  42654. this._inspector = new InspectorBase();
  42655. this._inspector.setRenderer( this );
  42656. /**
  42657. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  42658. *
  42659. * @private
  42660. * @type {?Function}
  42661. */
  42662. this._getFallback = getFallback;
  42663. /**
  42664. * A reference to a renderer module for managing shader attributes.
  42665. *
  42666. * @private
  42667. * @type {?Attributes}
  42668. * @default null
  42669. */
  42670. this._attributes = null;
  42671. /**
  42672. * A reference to a renderer module for managing geometries.
  42673. *
  42674. * @private
  42675. * @type {?Geometries}
  42676. * @default null
  42677. */
  42678. this._geometries = null;
  42679. /**
  42680. * A reference to a renderer module for managing node related logic.
  42681. *
  42682. * @private
  42683. * @type {?NodeManager}
  42684. * @default null
  42685. */
  42686. this._nodes = null;
  42687. /**
  42688. * A reference to a renderer module for managing the internal animation loop.
  42689. *
  42690. * @private
  42691. * @type {?Animation}
  42692. * @default null
  42693. */
  42694. this._animation = null;
  42695. /**
  42696. * A reference to a renderer module for managing shader program bindings.
  42697. *
  42698. * @private
  42699. * @type {?Bindings}
  42700. * @default null
  42701. */
  42702. this._bindings = null;
  42703. /**
  42704. * A reference to a renderer module for managing render objects.
  42705. *
  42706. * @private
  42707. * @type {?RenderObjects}
  42708. * @default null
  42709. */
  42710. this._objects = null;
  42711. /**
  42712. * A reference to a renderer module for managing render and compute pipelines.
  42713. *
  42714. * @private
  42715. * @type {?Pipelines}
  42716. * @default null
  42717. */
  42718. this._pipelines = null;
  42719. /**
  42720. * A reference to a renderer module for managing render bundles.
  42721. *
  42722. * @private
  42723. * @type {?RenderBundles}
  42724. * @default null
  42725. */
  42726. this._bundles = null;
  42727. /**
  42728. * A reference to a renderer module for managing render lists.
  42729. *
  42730. * @private
  42731. * @type {?RenderLists}
  42732. * @default null
  42733. */
  42734. this._renderLists = null;
  42735. /**
  42736. * A reference to a renderer module for managing render contexts.
  42737. *
  42738. * @private
  42739. * @type {?RenderContexts}
  42740. * @default null
  42741. */
  42742. this._renderContexts = null;
  42743. /**
  42744. * A reference to a renderer module for managing textures.
  42745. *
  42746. * @private
  42747. * @type {?Textures}
  42748. * @default null
  42749. */
  42750. this._textures = null;
  42751. /**
  42752. * A reference to a renderer module for backgrounds.
  42753. *
  42754. * @private
  42755. * @type {?Background}
  42756. * @default null
  42757. */
  42758. this._background = null;
  42759. /**
  42760. * Cache for the fullscreen quad.
  42761. * This fullscreen quad is used for internal render passes
  42762. * like the tone mapping and color space output pass.
  42763. *
  42764. * @private
  42765. * @type {Map<Texture,QuadMesh>}
  42766. */
  42767. this._quadCache = new Map();
  42768. /**
  42769. * A reference to the current render context.
  42770. *
  42771. * @private
  42772. * @type {?RenderContext}
  42773. * @default null
  42774. */
  42775. this._currentRenderContext = null;
  42776. /**
  42777. * A custom sort function for the opaque render list.
  42778. *
  42779. * @private
  42780. * @type {?Function}
  42781. * @default null
  42782. */
  42783. this._opaqueSort = null;
  42784. /**
  42785. * A custom sort function for the transparent render list.
  42786. *
  42787. * @private
  42788. * @type {?Function}
  42789. * @default null
  42790. */
  42791. this._transparentSort = null;
  42792. /**
  42793. * Cache of framebuffer targets per canvas target.
  42794. *
  42795. * @private
  42796. * @type {Map<CanvasTarget, RenderTarget>}
  42797. */
  42798. this._frameBufferTargets = new Map();
  42799. const alphaClear = this.alpha === true ? 0 : 1;
  42800. /**
  42801. * The clear color value.
  42802. *
  42803. * @private
  42804. * @type {Color4}
  42805. */
  42806. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  42807. /**
  42808. * The clear depth value.
  42809. *
  42810. * @private
  42811. * @type {number}
  42812. * @default 1
  42813. */
  42814. this._clearDepth = 1;
  42815. /**
  42816. * The clear stencil value.
  42817. *
  42818. * @private
  42819. * @type {number}
  42820. * @default 0
  42821. */
  42822. this._clearStencil = 0;
  42823. /**
  42824. * The current render target.
  42825. *
  42826. * @private
  42827. * @type {?RenderTarget}
  42828. * @default null
  42829. */
  42830. this._renderTarget = null;
  42831. /**
  42832. * The active cube face.
  42833. *
  42834. * @private
  42835. * @type {number}
  42836. * @default 0
  42837. */
  42838. this._activeCubeFace = 0;
  42839. /**
  42840. * The active mipmap level.
  42841. *
  42842. * @private
  42843. * @type {number}
  42844. * @default 0
  42845. */
  42846. this._activeMipmapLevel = 0;
  42847. /**
  42848. * The current output render target.
  42849. *
  42850. * @private
  42851. * @type {?RenderTarget}
  42852. * @default null
  42853. */
  42854. this._outputRenderTarget = null;
  42855. /**
  42856. * The MRT setting.
  42857. *
  42858. * @private
  42859. * @type {?MRTNode}
  42860. * @default null
  42861. */
  42862. this._mrt = null;
  42863. /**
  42864. * This function defines how a render object is going
  42865. * to be rendered.
  42866. *
  42867. * @private
  42868. * @type {?Function}
  42869. * @default null
  42870. */
  42871. this._renderObjectFunction = null;
  42872. /**
  42873. * Used to keep track of the current render object function.
  42874. *
  42875. * @private
  42876. * @type {?Function}
  42877. * @default null
  42878. */
  42879. this._currentRenderObjectFunction = null;
  42880. /**
  42881. * Used to keep track of the current render bundle.
  42882. *
  42883. * @private
  42884. * @type {?RenderBundle}
  42885. * @default null
  42886. */
  42887. this._currentRenderBundle = null;
  42888. /**
  42889. * Next to `_renderObjectFunction()`, this function provides another hook
  42890. * for influencing the render process of a render object. It is meant for internal
  42891. * use and only relevant for `compileAsync()` right now. Instead of using
  42892. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  42893. * a different function might be used which performs no draw but just the node
  42894. * and pipeline updates.
  42895. *
  42896. * @private
  42897. * @type {Function}
  42898. */
  42899. this._handleObjectFunction = this._renderObjectDirect;
  42900. /**
  42901. * Indicates whether the device has been lost or not. In WebGL terms, the device
  42902. * lost is considered as a context lost. When this is set to `true`, rendering
  42903. * isn't possible anymore.
  42904. *
  42905. * @private
  42906. * @type {boolean}
  42907. * @default false
  42908. */
  42909. this._isDeviceLost = false;
  42910. /**
  42911. * A callback function that defines what should happen when a device/context lost occurs.
  42912. *
  42913. * @type {Function}
  42914. */
  42915. this.onDeviceLost = this._onDeviceLost;
  42916. /**
  42917. * A callback function that defines what should happen when an uncaptured
  42918. * backend error is reported (e.g. a WebGPU validation/out-of-memory/internal
  42919. * error raised outside an error scope). Applications can override this to
  42920. * surface errors in their own UI without letting them escalate to a device
  42921. * loss. The default implementation logs to the console.
  42922. *
  42923. * @type {Function}
  42924. */
  42925. this.onError = this._onError;
  42926. /**
  42927. * Defines the type of output buffers. The default `HalfFloatType` is recommend for
  42928. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  42929. * This will reduce rendering quality though.
  42930. *
  42931. * @private
  42932. * @type {number}
  42933. * @default HalfFloatType
  42934. */
  42935. this._outputBufferType = outputBufferType;
  42936. /**
  42937. * A cache for shadow nodes per material
  42938. *
  42939. * @private
  42940. * @type {WeakMap<Material, Object>}
  42941. */
  42942. this._cacheShadowNodes = new WeakMap();
  42943. /**
  42944. * Whether the renderer has been initialized or not.
  42945. *
  42946. * @private
  42947. * @type {boolean}
  42948. * @default false
  42949. */
  42950. this._initialized = false;
  42951. /**
  42952. * The call depth of the renderer. Counts the number of
  42953. * nested render calls.
  42954. *
  42955. * @private
  42956. * @type {number}
  42957. * @default - 1
  42958. */
  42959. this._callDepth = -1;
  42960. /**
  42961. * A reference to the promise which initializes the renderer.
  42962. *
  42963. * @private
  42964. * @type {?Promise<this>}
  42965. * @default null
  42966. */
  42967. this._initPromise = null;
  42968. /**
  42969. * An array of compilation promises which are used in `compileAsync()`.
  42970. *
  42971. * @private
  42972. * @type {?Array<Promise>}
  42973. * @default null
  42974. */
  42975. this._compilationPromises = null;
  42976. /**
  42977. * Whether the renderer is currently precompiling a render object in
  42978. * `compileAsync()`.
  42979. *
  42980. * @private
  42981. * @type {boolean}
  42982. * @default false
  42983. */
  42984. this._isPreCompiling = false;
  42985. /**
  42986. * When an override material is in use, this property points to the current
  42987. * source material during the rendering of a render object.
  42988. *
  42989. * @private
  42990. * @type {?Material}
  42991. * @default null
  42992. */
  42993. this._currentSourceMaterial = null;
  42994. /**
  42995. * Whether the renderer should render transparent render objects or not.
  42996. *
  42997. * @type {boolean}
  42998. * @default true
  42999. */
  43000. this.transparent = true;
  43001. /**
  43002. * Whether the renderer should render opaque render objects or not.
  43003. *
  43004. * @type {boolean}
  43005. * @default true
  43006. */
  43007. this.opaque = true;
  43008. /**
  43009. * Shadow map configuration
  43010. * @typedef {Object} ShadowMapConfig
  43011. * @property {boolean} enabled - Whether to globally enable shadows or not.
  43012. * @property {boolean} transmitted - Whether to enable light transmission through non-opaque materials.
  43013. * @property {number} type - The shadow map type.
  43014. */
  43015. /**
  43016. * The renderer's shadow configuration.
  43017. *
  43018. * @type {ShadowMapConfig}
  43019. */
  43020. this.shadowMap = {
  43021. enabled: false,
  43022. transmitted: false,
  43023. type: PCFShadowMap
  43024. };
  43025. /**
  43026. * XR configuration.
  43027. * @typedef {Object} XRConfig
  43028. * @property {boolean} enabled - Whether to globally enable XR or not.
  43029. */
  43030. /**
  43031. * The renderer's XR manager.
  43032. *
  43033. * @type {XRManager}
  43034. */
  43035. this.xr = new XRManager( this, multiview );
  43036. /**
  43037. * Debug configuration.
  43038. * @typedef {Object} DebugConfig
  43039. * @property {boolean} checkShaderErrors - Whether shader errors should be checked or not.
  43040. * @property {Object} diagnostics - Diagnostics configuration for the shader generation.
  43041. * @property {boolean} diagnostics.keywords - Whether declaration names that collide with reserved keywords should be renamed or not.
  43042. * @property {?Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  43043. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  43044. */
  43045. /**
  43046. * The renderer's debug configuration.
  43047. *
  43048. * @type {DebugConfig}
  43049. */
  43050. this.debug = {
  43051. checkShaderErrors: true,
  43052. diagnostics: {
  43053. keywords: false
  43054. },
  43055. onShaderError: null,
  43056. getShaderAsync: async ( scene, camera, object ) => {
  43057. await this.compileAsync( object, camera, scene );
  43058. const useFrameBufferTarget = this.needsFrameBufferTarget && this._renderTarget === null;
  43059. const renderTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : ( this._renderTarget || this._outputRenderTarget );
  43060. const renderList = this._renderLists.get( scene, camera );
  43061. const renderContext = this._renderContexts.get( renderTarget, this._mrt );
  43062. const material = scene.overrideMaterial || object.material;
  43063. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  43064. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  43065. return { fragmentShader, vertexShader };
  43066. }
  43067. };
  43068. }
  43069. /**
  43070. * Initializes the renderer so it is ready for usage.
  43071. *
  43072. * @async
  43073. * @return {Promise<this>} A Promise that resolves when the renderer has been initialized.
  43074. */
  43075. async init() {
  43076. if ( this._initPromise !== null ) {
  43077. return this._initPromise;
  43078. }
  43079. this._initPromise = new Promise( async ( resolve, reject ) => {
  43080. let backend = this.backend;
  43081. try {
  43082. await backend.init( this );
  43083. } catch ( error ) {
  43084. if ( this._getFallback !== null ) {
  43085. // try the fallback
  43086. try {
  43087. this.backend = backend = this._getFallback( error );
  43088. await backend.init( this );
  43089. } catch ( error ) {
  43090. reject( error );
  43091. return;
  43092. }
  43093. } else {
  43094. reject( error );
  43095. return;
  43096. }
  43097. }
  43098. this._nodes = new NodeManager( this, backend );
  43099. this._animation = new Animation( this, this._nodes, this.info );
  43100. this._attributes = new Attributes( backend, this.info );
  43101. this._background = new Background( this, this._nodes );
  43102. this._geometries = new Geometries( this._attributes, this.info );
  43103. this._textures = new Textures( this, backend, this.info );
  43104. this._pipelines = new Pipelines( backend, this._nodes, this.info );
  43105. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  43106. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  43107. this._renderLists = new RenderLists( this.lighting );
  43108. this._bundles = new RenderBundles();
  43109. this._renderContexts = new RenderContexts( this );
  43110. //
  43111. this._animation.start();
  43112. this._initialized = true;
  43113. //
  43114. this._inspector.init();
  43115. //
  43116. resolve( this );
  43117. } );
  43118. return this._initPromise;
  43119. }
  43120. /**
  43121. * A reference to the canvas element the renderer is drawing to.
  43122. * This value of this property will automatically be created by
  43123. * the renderer.
  43124. *
  43125. * @type {HTMLCanvasElement|OffscreenCanvas}
  43126. */
  43127. get domElement() {
  43128. return this._canvasTarget.domElement;
  43129. }
  43130. /**
  43131. * The coordinate system of the renderer. The value of this property
  43132. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  43133. * `THREE.WebGPUCoordinateSystem`.
  43134. *
  43135. * @readonly
  43136. * @type {number}
  43137. */
  43138. get coordinateSystem() {
  43139. return this.backend.coordinateSystem;
  43140. }
  43141. /**
  43142. * Compiles all materials in the given scene. This can be useful to avoid a
  43143. * phenomenon which is called "shader compilation stutter", which occurs when
  43144. * rendering an object with a new shader for the first time.
  43145. *
  43146. * If you want to add a 3D object to an existing scene, use the third optional
  43147. * parameter for applying the target scene. Note that the (target) scene's lighting
  43148. * and environment must be configured before calling this method.
  43149. *
  43150. * @async
  43151. * @param {Object3D} scene - The scene or 3D object to precompile.
  43152. * @param {Camera} camera - The camera that is used to render the scene.
  43153. * @param {?Scene} targetScene - If the first argument is a 3D object, this parameter must represent the scene the 3D object is going to be added.
  43154. * @return {Promise} A Promise that resolves when the compile has been finished.
  43155. */
  43156. async compileAsync( scene, camera, targetScene = null ) {
  43157. if ( this._isDeviceLost === true ) return;
  43158. if ( this._initialized === false ) await this.init();
  43159. if ( this.shadowMap.type === PCFSoftShadowMap ) {
  43160. warn( 'WebGPURenderer: PCFSoftShadowMap has been removed. Using PCFShadowMap instead.' );
  43161. this.shadowMap.type = PCFShadowMap;
  43162. }
  43163. // preserve render tree
  43164. const nodeFrame = this._nodes.nodeFrame;
  43165. const previousRenderId = nodeFrame.renderId;
  43166. const previousRenderContext = this._currentRenderContext;
  43167. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  43168. const previousHandleObjectFunction = this._handleObjectFunction;
  43169. const previousCompilationPromises = this._compilationPromises;
  43170. //
  43171. if ( targetScene === null ) targetScene = scene;
  43172. // Use the actual scene for caching when compiling individual objects
  43173. // This ensures cache keys match between compileAsync and render
  43174. const sceneRef = ( scene.isScene === true ) ? scene : ( targetScene.isScene === true ) ? targetScene : _scene;
  43175. // Match render()'s logic: use frameBufferTarget when needsFrameBufferTarget is true
  43176. const useFrameBufferTarget = this.needsFrameBufferTarget && this._renderTarget === null;
  43177. const renderTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : ( this._renderTarget || this._outputRenderTarget );
  43178. const renderContext = this._renderContexts.get( renderTarget, this._mrt );
  43179. const activeMipmapLevel = this._activeMipmapLevel;
  43180. const compilationPromises = [];
  43181. this._currentRenderContext = renderContext;
  43182. this._currentRenderObjectFunction = this.renderObject;
  43183. this._handleObjectFunction = this._createObjectPipeline;
  43184. this._compilationPromises = compilationPromises;
  43185. nodeFrame.renderId ++;
  43186. //
  43187. nodeFrame.update();
  43188. //
  43189. renderContext.depth = this.depth;
  43190. renderContext.stencil = this.stencil;
  43191. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  43192. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  43193. //
  43194. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  43195. camera = this._updateCamera( camera );
  43196. //
  43197. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  43198. //
  43199. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  43200. if ( camera.isArrayCamera ) {
  43201. _frustumArray.setFromArrayCamera( camera );
  43202. } else {
  43203. _frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  43204. }
  43205. // Use sceneRef for render list to ensure lightsNode matches between compileAsync and render
  43206. const renderList = this._renderLists.get( sceneRef, camera );
  43207. renderList.begin();
  43208. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  43209. // include lights from target scene
  43210. if ( targetScene !== scene ) {
  43211. targetScene.traverseVisible( function ( object ) {
  43212. if ( object.isLight && object.layers.test( camera.layers ) ) {
  43213. renderList.pushLight( object );
  43214. }
  43215. } );
  43216. }
  43217. renderList.finish();
  43218. //
  43219. if ( renderTarget !== null ) {
  43220. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  43221. const renderTargetData = this._textures.get( renderTarget );
  43222. renderContext.textures = renderTargetData.textures;
  43223. renderContext.depthTexture = renderTargetData.depthTexture;
  43224. } else {
  43225. renderContext.textures = null;
  43226. renderContext.depthTexture = null;
  43227. }
  43228. //
  43229. if ( targetScene !== scene ) {
  43230. this._background.update( targetScene, renderList, renderContext );
  43231. } else {
  43232. this._background.update( sceneRef, renderList, renderContext );
  43233. }
  43234. // process render lists - _createObjectPipeline will push async promises to _compilationPromises
  43235. const opaqueObjects = renderList.opaque;
  43236. const transparentObjects = renderList.transparent;
  43237. const transparentDoublePassObjects = renderList.transparentDoublePass;
  43238. const lightsNode = renderList.lightsNode;
  43239. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  43240. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  43241. // restore render tree
  43242. nodeFrame.renderId = previousRenderId;
  43243. this._currentRenderContext = previousRenderContext;
  43244. this._currentRenderObjectFunction = previousRenderObjectFunction;
  43245. this._handleObjectFunction = previousHandleObjectFunction;
  43246. this._compilationPromises = previousCompilationPromises;
  43247. // Process compilation work items sequentially to avoid freezing
  43248. // Yields between objects to keep animation smooth
  43249. for ( const item of compilationPromises ) {
  43250. const renderObject = this._objects.get( item.object, item.material, item.scene, item.camera, item.lightsNode, item.renderContext, item.clippingContext, item.passId );
  43251. renderObject.drawRange = item.object.geometry.drawRange;
  43252. renderObject.group = item.group;
  43253. // Use async node building to yield to main thread
  43254. await this._nodes.getForRenderAsync( renderObject );
  43255. this._isPreCompiling = true; // note: no awaits are allowed when this flag is true otherwise the state leaks outside of this method
  43256. this._nodes.updateBefore( renderObject );
  43257. this._geometries.updateForRender( renderObject );
  43258. this._nodes.updateForRender( renderObject );
  43259. this._bindings.updateForRender( renderObject );
  43260. this._isPreCompiling = false;
  43261. // Wait for pipeline creation
  43262. const pipelinePromises = [];
  43263. this._pipelines.getForRender( renderObject, pipelinePromises );
  43264. if ( pipelinePromises.length > 0 ) {
  43265. await Promise.all( pipelinePromises );
  43266. }
  43267. this._isPreCompiling = true;
  43268. this._nodes.updateAfter( renderObject );
  43269. this._isPreCompiling = false;
  43270. // Yield between objects to allow animation frames
  43271. await yieldToMain();
  43272. }
  43273. }
  43274. /**
  43275. * Renders the scene in an async fashion.
  43276. *
  43277. * @async
  43278. * @deprecated
  43279. * @param {Object3D} scene - The scene or 3D object to render.
  43280. * @param {Camera} camera - The camera.
  43281. * @return {Promise} A Promise that resolves when the render has been finished.
  43282. */
  43283. async renderAsync( scene, camera ) {
  43284. warnOnce( 'Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  43285. await this.init();
  43286. this.render( scene, camera );
  43287. }
  43288. /**
  43289. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  43290. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  43291. *
  43292. * @async
  43293. * @deprecated
  43294. * @return {Promise} A Promise that resolves when synchronization has been finished.
  43295. */
  43296. async waitForGPU() {
  43297. error( 'Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.' );
  43298. }
  43299. //
  43300. set inspector( value ) {
  43301. if ( this._inspector !== null ) {
  43302. this._inspector.setRenderer( null );
  43303. }
  43304. this._inspector = value;
  43305. this._inspector.setRenderer( this );
  43306. }
  43307. /**
  43308. * The inspector instance. The inspector can be any class that extends from `InspectorBase`.
  43309. *
  43310. * @type {InspectorBase}
  43311. */
  43312. get inspector() {
  43313. return this._inspector;
  43314. }
  43315. /**
  43316. * Enables or disables high precision for model-view and normal-view matrices.
  43317. * When enabled, will use CPU 64-bit precision for higher precision instead of GPU 32-bit for higher performance.
  43318. *
  43319. * NOTE: 64-bit precision is not compatible with `InstancedMesh` and `SkinnedMesh`.
  43320. *
  43321. * @param {boolean} value - Whether to enable or disable high precision.
  43322. * @type {boolean}
  43323. */
  43324. set highPrecision( value ) {
  43325. const contextNodeData = this.contextNode.value;
  43326. if ( value === true ) {
  43327. contextNodeData.modelViewMatrix = highpModelViewMatrix;
  43328. contextNodeData.modelNormalViewMatrix = highpModelNormalViewMatrix;
  43329. } else if ( this.highPrecision ) {
  43330. delete contextNodeData.modelViewMatrix;
  43331. delete contextNodeData.modelNormalViewMatrix;
  43332. }
  43333. }
  43334. /**
  43335. * Returns whether high precision is enabled or not.
  43336. *
  43337. * @return {boolean} Whether high precision is enabled or not.
  43338. * @type {boolean}
  43339. */
  43340. get highPrecision() {
  43341. const contextNodeData = this.contextNode.value;
  43342. return contextNodeData.modelViewMatrix === highpModelViewMatrix && contextNodeData.modelNormalViewMatrix === highpModelNormalViewMatrix;
  43343. }
  43344. /**
  43345. * Sets the given MRT configuration.
  43346. *
  43347. * @param {MRTNode} mrt - The MRT node to set.
  43348. * @return {Renderer} A reference to this renderer.
  43349. */
  43350. setMRT( mrt ) {
  43351. this._mrt = mrt;
  43352. return this;
  43353. }
  43354. /**
  43355. * Returns the MRT configuration.
  43356. *
  43357. * @return {MRTNode} The MRT configuration.
  43358. */
  43359. getMRT() {
  43360. return this._mrt;
  43361. }
  43362. /**
  43363. * Returns the output buffer type.
  43364. *
  43365. * @return {number} The output buffer type.
  43366. */
  43367. getOutputBufferType() {
  43368. return this._outputBufferType;
  43369. }
  43370. /**
  43371. * Returns the output buffer type.
  43372. *
  43373. * @deprecated since r182. Use `.getOutputBufferType()` instead.
  43374. * @return {number} The output buffer type.
  43375. */
  43376. getColorBufferType() { // @deprecated, r182
  43377. warnOnce( 'Renderer: ".getColorBufferType()" has been renamed to ".getOutputBufferType()".' );
  43378. return this.getOutputBufferType();
  43379. }
  43380. /**
  43381. * Default implementation of the device lost callback.
  43382. *
  43383. * @private
  43384. * @param {Object} info - Information about the context lost.
  43385. */
  43386. _onDeviceLost( info ) {
  43387. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  43388. if ( info.reason ) {
  43389. errorMessage += `\nReason: ${info.reason}`;
  43390. }
  43391. error( errorMessage );
  43392. this._isDeviceLost = true;
  43393. }
  43394. /**
  43395. * Default implementation of the uncaptured backend error callback.
  43396. *
  43397. * @private
  43398. * @param {Object} info - Information about the uncaptured error.
  43399. */
  43400. _onError( info ) {
  43401. let errorMessage = `WebGPURenderer: Uncaptured ${ info.api } ${ info.type }`;
  43402. if ( info.message ) {
  43403. errorMessage += `: ${ info.message }`;
  43404. }
  43405. error( errorMessage );
  43406. }
  43407. /**
  43408. * Returns `true` if the cached GPU render bundle for the given bundle group is
  43409. * out-of-date and must be recorded again.
  43410. *
  43411. * @private
  43412. * @param {BundleGroup} bundleGroup - The bundle group.
  43413. * @param {Object} renderBundleData - The backend data of the render bundle.
  43414. * @return {boolean} Whether the cached render bundle needs an update.
  43415. */
  43416. _bundleNeedsUpdate( bundleGroup, renderBundleData ) {
  43417. return renderBundleData.bundleGPU === undefined || bundleGroup.version !== renderBundleData.version;
  43418. }
  43419. /**
  43420. * Renders the given render bundle.
  43421. *
  43422. * @private
  43423. * @param {Object} bundle - Render bundle data.
  43424. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  43425. * @param {LightsNode} lightsNode - The lights node.
  43426. */
  43427. _renderBundle( bundle, sceneRef, lightsNode ) {
  43428. const { bundleGroup, camera, renderList } = bundle;
  43429. const renderContext = this._currentRenderContext;
  43430. //
  43431. const renderBundle = this._bundles.get( bundleGroup, camera, renderContext );
  43432. const renderBundleData = this.backend.get( renderBundle );
  43433. const renderBundleNeedsUpdate = this._bundleNeedsUpdate( bundleGroup, renderBundleData );
  43434. if ( renderBundleNeedsUpdate ) {
  43435. this.backend.beginBundle( renderContext );
  43436. this._currentRenderBundle = renderBundle;
  43437. const {
  43438. transparentDoublePass: transparentDoublePassObjects,
  43439. transparent: transparentObjects,
  43440. opaque: opaqueObjects
  43441. } = renderList;
  43442. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  43443. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  43444. this._currentRenderBundle = null;
  43445. //
  43446. this.backend.finishBundle( renderContext, renderBundle );
  43447. renderBundleData.version = bundleGroup.version;
  43448. } else {
  43449. const { renderObjects } = renderBundleData;
  43450. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  43451. const renderObject = renderObjects[ i ];
  43452. if ( this._nodes.needsRefresh( renderObject ) ) {
  43453. this._nodes.updateBefore( renderObject );
  43454. this._geometries.updateForRender( renderObject );
  43455. this._nodes.updateForRender( renderObject );
  43456. this._bindings.updateForRender( renderObject );
  43457. this._nodes.updateAfter( renderObject );
  43458. }
  43459. }
  43460. }
  43461. this.backend.addBundle( renderContext, renderBundle );
  43462. }
  43463. /**
  43464. * Renders the scene or 3D object with the given camera. This method can only be called
  43465. * if the renderer has been initialized. When using `render()` inside an animation loop,
  43466. * it's guaranteed the renderer will be initialized. The animation loop must be defined
  43467. * with {@link Renderer#setAnimationLoop} though.
  43468. *
  43469. * For all other use cases (like when using on-demand rendering), you must call
  43470. * {@link Renderer#init} before rendering.
  43471. *
  43472. * The target of the method is the default framebuffer (meaning the canvas)
  43473. * or alternatively a render target when specified via `setRenderTarget()`.
  43474. *
  43475. * @param {Object3D} scene - The scene or 3D object to render.
  43476. * @param {Camera} camera - The camera to render the scene with.
  43477. */
  43478. render( scene, camera ) {
  43479. if ( this._initialized === false ) {
  43480. throw new Error( 'THREE.Renderer: .render() called before the backend is initialized. Use "await renderer.init();" before rendering.' );
  43481. }
  43482. this._renderScene( scene, camera );
  43483. }
  43484. /**
  43485. * Returns whether the renderer has been initialized or not.
  43486. *
  43487. * @readonly
  43488. * @return {boolean} Whether the renderer has been initialized or not.
  43489. */
  43490. get initialized() {
  43491. return this._initialized;
  43492. }
  43493. _renderOutputLayers( quad, renderTarget ) {
  43494. if ( renderTarget.texture.isArrayTexture !== true || renderTarget.texture.image.depth <= 1 ) {
  43495. this._renderScene( quad, quad.camera, false );
  43496. return;
  43497. }
  43498. const currentActiveCubeFace = this._activeCubeFace;
  43499. try {
  43500. for ( let layer = 0; layer < renderTarget.texture.image.depth; layer ++ ) {
  43501. this._nodes.setOutputLayerIndex( layer );
  43502. this._activeCubeFace = layer;
  43503. this._renderScene( quad, quad.camera, false );
  43504. }
  43505. } finally {
  43506. this._nodes.setOutputLayerIndex( 0 );
  43507. this._activeCubeFace = currentActiveCubeFace;
  43508. }
  43509. }
  43510. /**
  43511. * Returns an internal render target which is used when computing the output tone mapping
  43512. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  43513. * pass and not inline to achieve more correct results.
  43514. *
  43515. * @private
  43516. * @return {?RenderTarget} The render target. The method returns `null` if no output conversion should be applied.
  43517. */
  43518. _getFrameBufferTarget() {
  43519. const { currentToneMapping, currentColorSpace } = this;
  43520. const useToneMapping = currentToneMapping !== NoToneMapping;
  43521. const useColorSpace = currentColorSpace !== ColorManagement.workingColorSpace;
  43522. if ( useToneMapping === false && useColorSpace === false ) return null;
  43523. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  43524. const { depth, stencil } = this;
  43525. // TODO: Unify CanvasTarget and OutputRenderTarget
  43526. const target = this._outputRenderTarget || this._canvasTarget;
  43527. let frameBufferTarget = this._frameBufferTargets.get( target );
  43528. if ( frameBufferTarget === undefined ) {
  43529. frameBufferTarget = new RenderTarget( width, height, {
  43530. depthBuffer: depth,
  43531. stencilBuffer: stencil,
  43532. type: this._outputBufferType,
  43533. format: RGBAFormat,
  43534. colorSpace: ColorManagement.workingColorSpace,
  43535. generateMipmaps: false,
  43536. minFilter: LinearFilter,
  43537. magFilter: LinearFilter,
  43538. samples: this.samples
  43539. } );
  43540. frameBufferTarget.isPostProcessingRenderTarget = true;
  43541. const dispose = () => {
  43542. target.removeEventListener( 'dispose', dispose );
  43543. frameBufferTarget.dispose();
  43544. this._frameBufferTargets.delete( target );
  43545. };
  43546. target.addEventListener( 'dispose', dispose );
  43547. this._frameBufferTargets.set( target, frameBufferTarget );
  43548. }
  43549. const outputRenderTarget = this.getOutputRenderTarget();
  43550. frameBufferTarget.depthBuffer = depth;
  43551. frameBufferTarget.stencilBuffer = stencil;
  43552. if ( outputRenderTarget !== null ) {
  43553. frameBufferTarget.setSize( outputRenderTarget.width, outputRenderTarget.height, outputRenderTarget.depth );
  43554. } else {
  43555. frameBufferTarget.setSize( width, height, 1 );
  43556. }
  43557. // RenderTarget || CanvasTarget
  43558. const viewport = this._outputRenderTarget ? this._outputRenderTarget.viewport : target._viewport;
  43559. const scissor = this._outputRenderTarget ? this._outputRenderTarget.scissor : target._scissor;
  43560. const pixelRatio = this._outputRenderTarget ? 1 : target._pixelRatio;
  43561. const scissorTest = this._outputRenderTarget ? this._outputRenderTarget.scissorTest : target._scissorTest;
  43562. frameBufferTarget.viewport.copy( viewport );
  43563. frameBufferTarget.scissor.copy( scissor );
  43564. frameBufferTarget.viewport.multiplyScalar( pixelRatio );
  43565. frameBufferTarget.scissor.multiplyScalar( pixelRatio );
  43566. frameBufferTarget.scissorTest = scissorTest;
  43567. frameBufferTarget.multiview = outputRenderTarget !== null ? outputRenderTarget.multiview : false;
  43568. frameBufferTarget.useArrayDepthTexture = outputRenderTarget !== null ? outputRenderTarget.useArrayDepthTexture : false;
  43569. frameBufferTarget.resolveDepthBuffer = outputRenderTarget !== null ? outputRenderTarget.resolveDepthBuffer : true;
  43570. frameBufferTarget.resolveStencilBuffer = outputRenderTarget !== null ? outputRenderTarget.resolveStencilBuffer : true;
  43571. frameBufferTarget.storeMultisampledColorBuffer = outputRenderTarget !== null ? outputRenderTarget.storeMultisampledColorBuffer : true;
  43572. frameBufferTarget.storeMultisampledDepthBuffer = outputRenderTarget !== null ? outputRenderTarget.storeMultisampledDepthBuffer : true;
  43573. frameBufferTarget.storeMultisampledStencilBuffer = outputRenderTarget !== null ? outputRenderTarget.storeMultisampledStencilBuffer : true;
  43574. frameBufferTarget._autoAllocateDepthBuffer = outputRenderTarget !== null ? outputRenderTarget._autoAllocateDepthBuffer : false;
  43575. return frameBufferTarget;
  43576. }
  43577. /**
  43578. * Renders the scene or 3D object with the given camera.
  43579. *
  43580. * @private
  43581. * @param {Object3D} scene - The scene or 3D object to render.
  43582. * @param {Camera} camera - The camera to render the scene with.
  43583. * @param {boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  43584. * @return {RenderContext} The current render context.
  43585. */
  43586. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  43587. if ( this._isDeviceLost === true ) return;
  43588. if ( this.shadowMap.type === PCFSoftShadowMap ) {
  43589. warn( 'WebGPURenderer: PCFSoftShadowMap has been removed. Using PCFShadowMap instead.' );
  43590. this.shadowMap.type = PCFShadowMap;
  43591. }
  43592. //
  43593. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  43594. // preserve render tree
  43595. const nodeFrame = this._nodes.nodeFrame;
  43596. const previousRenderId = nodeFrame.renderId;
  43597. const previousRenderContext = this._currentRenderContext;
  43598. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  43599. const previousHandleObjectFunction = this._handleObjectFunction;
  43600. this.lighting.beginRender( scene );
  43601. //
  43602. this._callDepth ++;
  43603. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  43604. const outputRenderTarget = this._renderTarget || this._outputRenderTarget;
  43605. const activeCubeFace = this._activeCubeFace;
  43606. const activeMipmapLevel = this._activeMipmapLevel;
  43607. //
  43608. let renderTarget;
  43609. if ( frameBufferTarget !== null ) {
  43610. renderTarget = frameBufferTarget;
  43611. this.setRenderTarget( renderTarget );
  43612. } else {
  43613. renderTarget = outputRenderTarget;
  43614. }
  43615. // make sure a new render target has correct default depth values
  43616. if ( renderTarget !== null && renderTarget.depthBuffer === true ) {
  43617. const renderTargetData = this._textures.get( renderTarget );
  43618. if ( renderTargetData.depthInitialized !== true ) {
  43619. // we need a single manual clear if auto clear depth is disabled
  43620. if ( this.autoClear === false || ( this.autoClear === true && this.autoClearDepth === false ) ) {
  43621. this.clearDepth();
  43622. }
  43623. renderTargetData.depthInitialized = true;
  43624. }
  43625. }
  43626. //
  43627. const renderContext = this._renderContexts.get( renderTarget, this._mrt, this._callDepth );
  43628. this._currentRenderContext = renderContext;
  43629. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  43630. this._handleObjectFunction = this._renderObjectDirect;
  43631. //
  43632. this.info.calls ++;
  43633. this.info.render.calls ++;
  43634. this.info.render.frameCalls ++;
  43635. nodeFrame.renderId = this.info.calls;
  43636. //
  43637. this.backend.updateTimeStampUID( renderContext );
  43638. this.inspector.beginRender( this.backend.getTimestampUID( renderContext ), scene, camera, renderTarget );
  43639. //
  43640. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  43641. camera = this._updateCamera( camera );
  43642. //
  43643. const canvasTarget = this._canvasTarget;
  43644. let viewport = canvasTarget._viewport;
  43645. let scissor = canvasTarget._scissor;
  43646. let pixelRatio = canvasTarget._pixelRatio;
  43647. if ( renderTarget !== null ) {
  43648. viewport = renderTarget.viewport;
  43649. scissor = renderTarget.scissor;
  43650. pixelRatio = 1;
  43651. }
  43652. this.getDrawingBufferSize( _drawingBufferSize );
  43653. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  43654. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  43655. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  43656. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  43657. renderContext.viewportValue.width >>= activeMipmapLevel;
  43658. renderContext.viewportValue.height >>= activeMipmapLevel;
  43659. renderContext.viewportValue.minDepth = minDepth;
  43660. renderContext.viewportValue.maxDepth = maxDepth;
  43661. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  43662. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  43663. renderContext.scissor = canvasTarget._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  43664. renderContext.scissorValue.width >>= activeMipmapLevel;
  43665. renderContext.scissorValue.height >>= activeMipmapLevel;
  43666. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  43667. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  43668. //
  43669. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  43670. //
  43671. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  43672. if ( camera.isArrayCamera ) {
  43673. _frustumArray.setFromArrayCamera( camera );
  43674. } else {
  43675. _frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  43676. }
  43677. this._renderLists.update( nodeFrame.frameId );
  43678. const renderList = this._renderLists.get( scene, camera );
  43679. renderList.begin();
  43680. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  43681. renderList.finish();
  43682. if ( this.sortObjects === true ) {
  43683. renderList.sort( this._opaqueSort, this._transparentSort );
  43684. }
  43685. //
  43686. if ( renderTarget !== null ) {
  43687. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  43688. const renderTargetData = this._textures.get( renderTarget );
  43689. renderContext.textures = renderTargetData.textures;
  43690. renderContext.depthTexture = renderTargetData.depthTexture;
  43691. renderContext.width = renderTargetData.width;
  43692. renderContext.height = renderTargetData.height;
  43693. renderContext.renderTarget = renderTarget;
  43694. renderContext.depth = renderTarget.depthBuffer;
  43695. renderContext.stencil = renderTarget.stencilBuffer;
  43696. } else {
  43697. renderContext.textures = null;
  43698. renderContext.depthTexture = null;
  43699. renderContext.width = _drawingBufferSize.width;
  43700. renderContext.height = _drawingBufferSize.height;
  43701. renderContext.depth = this.depth;
  43702. renderContext.stencil = this.stencil;
  43703. }
  43704. renderContext.width >>= activeMipmapLevel;
  43705. renderContext.height >>= activeMipmapLevel;
  43706. renderContext.activeCubeFace = activeCubeFace;
  43707. renderContext.activeMipmapLevel = activeMipmapLevel;
  43708. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  43709. renderContext.fullscreenPass = scene.isQuadMesh === true;
  43710. //
  43711. renderContext.scissorValue.max( _vector4.set( 0, 0, 0, 0 ) );
  43712. if ( renderContext.scissorValue.x + renderContext.scissorValue.width > renderContext.width ) {
  43713. renderContext.scissorValue.width = Math.max( renderContext.width - renderContext.scissorValue.x, 0 );
  43714. }
  43715. if ( renderContext.scissorValue.y + renderContext.scissorValue.height > renderContext.height ) {
  43716. renderContext.scissorValue.height = Math.max( renderContext.height - renderContext.scissorValue.y, 0 );
  43717. }
  43718. //
  43719. this._background.update( sceneRef, renderList, renderContext );
  43720. //
  43721. renderContext.camera = camera;
  43722. this.backend.beginRender( renderContext );
  43723. // process render lists
  43724. const {
  43725. bundles,
  43726. lightsNode,
  43727. transparentDoublePass: transparentDoublePassObjects,
  43728. transparent: transparentObjects,
  43729. opaque: opaqueObjects
  43730. } = renderList;
  43731. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  43732. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  43733. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  43734. // finish render pass
  43735. this.backend.finishRender( renderContext );
  43736. // restore render tree
  43737. nodeFrame.renderId = previousRenderId;
  43738. this._currentRenderContext = previousRenderContext;
  43739. this._currentRenderObjectFunction = previousRenderObjectFunction;
  43740. this._handleObjectFunction = previousHandleObjectFunction;
  43741. this.lighting.finishRender( scene );
  43742. //
  43743. this._callDepth --;
  43744. if ( frameBufferTarget !== null ) {
  43745. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  43746. this._renderOutput( renderTarget );
  43747. }
  43748. //
  43749. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  43750. //
  43751. this.inspector.finishRender( this.backend.getTimestampUID( renderContext ) );
  43752. //
  43753. return renderContext;
  43754. }
  43755. _setXRLayerSize( width, height ) {
  43756. // TODO: Find a better solution to resize the canvas when in XR.
  43757. this._canvasTarget._width = width;
  43758. this._canvasTarget._height = height;
  43759. this.setViewport( 0, 0, width, height );
  43760. }
  43761. /**
  43762. * The output pass performs tone mapping and color space conversion.
  43763. *
  43764. * @private
  43765. * @param {RenderTarget} renderTarget - The current render target.
  43766. */
  43767. _renderOutput( renderTarget ) {
  43768. const cacheKey = this._nodes.getOutputCacheKey();
  43769. let quadData = this._quadCache.get( renderTarget.texture );
  43770. let quad;
  43771. if ( quadData === undefined ) {
  43772. quad = new QuadMesh( new NodeMaterial() );
  43773. quad.name = 'Output Color Transform';
  43774. quad.material.name = 'outputColorTransform';
  43775. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  43776. quadData = {
  43777. quad,
  43778. cacheKey
  43779. };
  43780. this._quadCache.set( renderTarget.texture, quadData );
  43781. // dispose logic
  43782. const dispose = () => {
  43783. quad.material.dispose();
  43784. this._quadCache.delete( renderTarget.texture );
  43785. renderTarget.texture.removeEventListener( 'dispose', dispose );
  43786. };
  43787. renderTarget.texture.addEventListener( 'dispose', dispose );
  43788. } else {
  43789. quad = quadData.quad;
  43790. if ( quadData.cacheKey !== cacheKey ) {
  43791. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  43792. quad.material.needsUpdate = true;
  43793. quadData.cacheKey = cacheKey;
  43794. }
  43795. }
  43796. // a clear operation clears the intermediate renderTarget texture, but should not update the screen canvas.
  43797. const currentAutoClear = this.autoClear;
  43798. const currentXR = this.xr.enabled;
  43799. this.autoClear = false;
  43800. this.xr.enabled = false;
  43801. this._renderOutputLayers( quad, renderTarget );
  43802. this.autoClear = currentAutoClear;
  43803. this.xr.enabled = currentXR;
  43804. }
  43805. /**
  43806. * Returns the maximum available anisotropy for texture filtering.
  43807. *
  43808. * @return {number} The maximum available anisotropy.
  43809. */
  43810. getMaxAnisotropy() {
  43811. return this.backend.capabilities.getMaxAnisotropy();
  43812. }
  43813. /**
  43814. * Returns the active cube face.
  43815. *
  43816. * @return {number} The active cube face.
  43817. */
  43818. getActiveCubeFace() {
  43819. return this._activeCubeFace;
  43820. }
  43821. /**
  43822. * Returns the active mipmap level.
  43823. *
  43824. * @return {number} The active mipmap level.
  43825. */
  43826. getActiveMipmapLevel() {
  43827. return this._activeMipmapLevel;
  43828. }
  43829. /**
  43830. * Applications are advised to always define the animation loop
  43831. * with this method and not manually with `requestAnimationFrame()`
  43832. * for best compatibility.
  43833. *
  43834. * @async
  43835. * @param {?onAnimationCallback} callback - The application's animation loop.
  43836. * @return {Promise} A Promise that resolves when the set has been executed.
  43837. */
  43838. async setAnimationLoop( callback ) {
  43839. if ( this._initialized === false ) await this.init();
  43840. this._animation.setAnimationLoop( callback );
  43841. }
  43842. /**
  43843. * Returns the current animation loop callback.
  43844. *
  43845. * @return {?Function} The current animation loop callback.
  43846. */
  43847. getAnimationLoop() {
  43848. return this._animation.getAnimationLoop();
  43849. }
  43850. /**
  43851. * Can be used to transfer buffer data from a storage buffer attribute
  43852. * from the GPU to the CPU in context of compute shaders.
  43853. *
  43854. * @async
  43855. * @param {BufferAttribute} attribute - The storage buffer attribute to read frm.
  43856. * @param {ReadbackBuffer|ArrayBuffer} target - The storage buffer attribute.
  43857. * @param {number} offset - The storage buffer attribute.
  43858. * @param {number} count - The offset from which to start reading the
  43859. * @return {Promise<ArrayBuffer|ReadbackBuffer>} A promise that resolves with the buffer data when the data are ready.
  43860. */
  43861. async getArrayBufferAsync( attribute, target = null, offset = 0, count = -1 ) {
  43862. // tally the memory for this readback buffer
  43863. if ( target !== null && target.isReadbackBuffer ) {
  43864. if ( this.info.memoryMap.has( target ) === false ) {
  43865. this.info.createReadbackBuffer( target );
  43866. const disposeInfo = () => {
  43867. target.removeEventListener( 'dispose', disposeInfo );
  43868. this.info.destroyReadbackBuffer( target );
  43869. };
  43870. target.addEventListener( 'dispose', disposeInfo );
  43871. }
  43872. }
  43873. if ( offset % 4 !== 0 || ( count > 0 && count % 4 !== 0 ) ) {
  43874. throw new Error( 'THREE.Renderer: "getArrayBufferAsync()" offset and count must be a multiple of 4.' );
  43875. }
  43876. return await this.backend.getArrayBufferAsync( attribute, target, offset, count );
  43877. }
  43878. /**
  43879. * Returns the rendering context.
  43880. *
  43881. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  43882. */
  43883. getContext() {
  43884. return this.backend.getContext();
  43885. }
  43886. /**
  43887. * Returns the pixel ratio.
  43888. *
  43889. * @return {number} The pixel ratio.
  43890. */
  43891. getPixelRatio() {
  43892. return this._canvasTarget.getPixelRatio();
  43893. }
  43894. /**
  43895. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  43896. *
  43897. * @param {Vector2} target - The method writes the result in this target object.
  43898. * @return {Vector2} The drawing buffer size.
  43899. */
  43900. getDrawingBufferSize( target ) {
  43901. return this._canvasTarget.getDrawingBufferSize( target );
  43902. }
  43903. /**
  43904. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  43905. *
  43906. * @param {Vector2} target - The method writes the result in this target object.
  43907. * @return {Vector2} The renderer's size in logical pixels.
  43908. */
  43909. getSize( target ) {
  43910. return this._canvasTarget.getSize( target );
  43911. }
  43912. /**
  43913. * Sets the given pixel ratio and resizes the canvas if necessary.
  43914. *
  43915. * @param {number} [value=1] - The pixel ratio.
  43916. */
  43917. setPixelRatio( value = 1 ) {
  43918. this._canvasTarget.setPixelRatio( value );
  43919. }
  43920. /**
  43921. * This method allows to define the drawing buffer size by specifying
  43922. * width, height and pixel ratio all at once. The size of the drawing
  43923. * buffer is computed with this formula:
  43924. * ```js
  43925. * size.x = width * pixelRatio;
  43926. * size.y = height * pixelRatio;
  43927. * ```
  43928. *
  43929. * @param {number} width - The width in logical pixels.
  43930. * @param {number} height - The height in logical pixels.
  43931. * @param {number} pixelRatio - The pixel ratio.
  43932. */
  43933. setDrawingBufferSize( width, height, pixelRatio ) {
  43934. // Renderer can't be resized while presenting in XR.
  43935. if ( this.xr && this.xr.isPresenting ) return;
  43936. this._canvasTarget.setDrawingBufferSize( width, height, pixelRatio );
  43937. }
  43938. /**
  43939. * Sets the size of the renderer.
  43940. *
  43941. * @param {number} width - The width in logical pixels.
  43942. * @param {number} height - The height in logical pixels.
  43943. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  43944. */
  43945. setSize( width, height, updateStyle = true ) {
  43946. // Renderer can't be resized while presenting in XR.
  43947. if ( this.xr && this.xr.isPresenting ) return;
  43948. this._canvasTarget.setSize( width, height, updateStyle );
  43949. }
  43950. /**
  43951. * Defines a manual sort function for the opaque render list.
  43952. * Pass `null` to use the default sort.
  43953. *
  43954. * @param {Function} method - The sort function.
  43955. */
  43956. setOpaqueSort( method ) {
  43957. this._opaqueSort = method;
  43958. }
  43959. /**
  43960. * Defines a manual sort function for the transparent render list.
  43961. * Pass `null` to use the default sort.
  43962. *
  43963. * @param {Function} method - The sort function.
  43964. */
  43965. setTransparentSort( method ) {
  43966. this._transparentSort = method;
  43967. }
  43968. /**
  43969. * Returns the scissor rectangle.
  43970. *
  43971. * @param {Vector4} target - The method writes the result in this target object.
  43972. * @return {Vector4} The scissor rectangle.
  43973. */
  43974. getScissor( target ) {
  43975. return this._canvasTarget.getScissor( target );
  43976. }
  43977. /**
  43978. * Defines the scissor rectangle.
  43979. *
  43980. * @param {number | Vector4} x - The horizontal coordinate for the upper left corner of the box in logical pixel unit.
  43981. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  43982. * @param {number} y - The vertical coordinate for the upper left corner of the box in logical pixel unit.
  43983. * @param {number} width - The width of the scissor box in logical pixel unit.
  43984. * @param {number} height - The height of the scissor box in logical pixel unit.
  43985. */
  43986. setScissor( x, y, width, height ) {
  43987. this._canvasTarget.setScissor( x, y, width, height );
  43988. }
  43989. /**
  43990. * Returns the scissor test value.
  43991. *
  43992. * @return {boolean} Whether the scissor test should be enabled or not.
  43993. */
  43994. getScissorTest() {
  43995. return this._canvasTarget.getScissorTest();
  43996. }
  43997. /**
  43998. * Defines the scissor test.
  43999. *
  44000. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  44001. */
  44002. setScissorTest( boolean ) {
  44003. this._canvasTarget.setScissorTest( boolean );
  44004. // TODO: Move it to CanvasTarget event listener.
  44005. this.backend.setScissorTest( boolean );
  44006. }
  44007. /**
  44008. * Resets the backend's internal state cache. Useful when the rendering context is shared with
  44009. * other libraries that change the state. A no-op for the WebGPU backend.
  44010. */
  44011. resetState() {
  44012. if ( this._initialized === false ) {
  44013. throw new Error( 'THREE.Renderer: .resetState() called before the backend is initialized. Use "await renderer.init();" before using this method.' );
  44014. }
  44015. this.backend.resetState();
  44016. }
  44017. /**
  44018. * Returns the viewport definition.
  44019. *
  44020. * @param {Vector4} target - The method writes the result in this target object.
  44021. * @return {Vector4} The viewport definition.
  44022. */
  44023. getViewport( target ) {
  44024. return this._canvasTarget.getViewport( target );
  44025. }
  44026. /**
  44027. * Defines the viewport.
  44028. *
  44029. * @param {number | Vector4} x - The horizontal coordinate for the upper left corner of the viewport origin in logical pixel unit.
  44030. * @param {number} y - The vertical coordinate for the upper left corner of the viewport origin in logical pixel unit.
  44031. * @param {number} width - The width of the viewport in logical pixel unit.
  44032. * @param {number} height - The height of the viewport in logical pixel unit.
  44033. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  44034. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  44035. */
  44036. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  44037. this._canvasTarget.setViewport( x, y, width, height, minDepth, maxDepth );
  44038. }
  44039. /**
  44040. * Returns the clear color.
  44041. *
  44042. * @param {Color} target - The method writes the result in this target object.
  44043. * @return {Color} The clear color.
  44044. */
  44045. getClearColor( target ) {
  44046. return target.copy( this._clearColor );
  44047. }
  44048. /**
  44049. * Defines the clear color and optionally the clear alpha.
  44050. *
  44051. * @param {Color} color - The clear color.
  44052. * @param {number} [alpha=1] - The clear alpha.
  44053. */
  44054. setClearColor( color, alpha = 1 ) {
  44055. this._clearColor.set( color );
  44056. this._clearColor.a = alpha;
  44057. }
  44058. /**
  44059. * Returns the clear alpha.
  44060. *
  44061. * @return {number} The clear alpha.
  44062. */
  44063. getClearAlpha() {
  44064. return this._clearColor.a;
  44065. }
  44066. /**
  44067. * Defines the clear alpha.
  44068. *
  44069. * @param {number} alpha - The clear alpha.
  44070. */
  44071. setClearAlpha( alpha ) {
  44072. this._clearColor.a = alpha;
  44073. }
  44074. /**
  44075. * Returns the clear depth.
  44076. *
  44077. * @return {number} The clear depth.
  44078. */
  44079. getClearDepth() {
  44080. return ( this.reversedDepthBuffer === true ) ? 1 - this._clearDepth : this._clearDepth;
  44081. }
  44082. /**
  44083. * Defines the clear depth.
  44084. *
  44085. * @param {number} depth - The clear depth.
  44086. */
  44087. setClearDepth( depth ) {
  44088. this._clearDepth = depth;
  44089. }
  44090. /**
  44091. * Returns the clear stencil.
  44092. *
  44093. * @return {number} The clear stencil.
  44094. */
  44095. getClearStencil() {
  44096. return this._clearStencil;
  44097. }
  44098. /**
  44099. * Defines the clear stencil.
  44100. *
  44101. * @param {number} stencil - The clear stencil.
  44102. */
  44103. setClearStencil( stencil ) {
  44104. this._clearStencil = stencil;
  44105. }
  44106. /**
  44107. * This method performs an occlusion query for the given 3D object.
  44108. * It returns `true` if the given 3D object is fully occluded by other
  44109. * 3D objects in the scene.
  44110. *
  44111. * @param {Object3D} object - The 3D object to test.
  44112. * @return {boolean} Whether the 3D object is fully occluded or not.
  44113. */
  44114. isOccluded( object ) {
  44115. const renderContext = this._currentRenderContext;
  44116. return renderContext && this.backend.isOccluded( renderContext, object );
  44117. }
  44118. /**
  44119. * Performs a manual clear operation. This method ignores `autoClear` properties.
  44120. *
  44121. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  44122. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  44123. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  44124. */
  44125. clear( color = true, depth = true, stencil = true ) {
  44126. if ( this._initialized === false ) {
  44127. throw new Error( 'THREE.Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before using this method.' );
  44128. }
  44129. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  44130. let renderContext = null;
  44131. if ( renderTarget !== null ) {
  44132. this._textures.updateRenderTarget( renderTarget );
  44133. const renderTargetData = this._textures.get( renderTarget );
  44134. renderContext = this._renderContexts.get( renderTarget, null, -1 ); // using - 1 for the call depth to get a render context for the clear operation
  44135. renderContext.textures = renderTargetData.textures;
  44136. renderContext.depthTexture = renderTargetData.depthTexture;
  44137. renderContext.width = renderTargetData.width;
  44138. renderContext.height = renderTargetData.height;
  44139. renderContext.renderTarget = renderTarget;
  44140. renderContext.depth = renderTarget.depthBuffer;
  44141. renderContext.stencil = renderTarget.stencilBuffer;
  44142. // #30329
  44143. const color = this.backend.getClearColor();
  44144. renderContext.clearColorValue.r = color.r;
  44145. renderContext.clearColorValue.g = color.g;
  44146. renderContext.clearColorValue.b = color.b;
  44147. renderContext.clearColorValue.a = color.a;
  44148. renderContext.clearDepthValue = this.getClearDepth();
  44149. renderContext.clearStencilValue = this.getClearStencil();
  44150. renderContext.activeCubeFace = this.getActiveCubeFace();
  44151. renderContext.activeMipmapLevel = this.getActiveMipmapLevel();
  44152. if ( renderTarget.depthBuffer === true ) renderTargetData.depthInitialized = true;
  44153. }
  44154. this.backend.clear( color, depth, stencil, renderContext );
  44155. if ( renderTarget !== null && this._renderTarget === null ) {
  44156. this._renderOutput( renderTarget );
  44157. }
  44158. }
  44159. /**
  44160. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  44161. */
  44162. clearColor() {
  44163. this.clear( true, false, false );
  44164. }
  44165. /**
  44166. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  44167. */
  44168. clearDepth() {
  44169. this.clear( false, true, false );
  44170. }
  44171. /**
  44172. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  44173. */
  44174. clearStencil() {
  44175. this.clear( false, false, true );
  44176. }
  44177. /**
  44178. * Async version of {@link Renderer#clear}.
  44179. *
  44180. * @async
  44181. * @deprecated
  44182. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  44183. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  44184. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  44185. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  44186. */
  44187. async clearAsync( color = true, depth = true, stencil = true ) {
  44188. warnOnce( 'Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  44189. await this.init();
  44190. this.clear( color, depth, stencil );
  44191. }
  44192. /**
  44193. * Async version of {@link Renderer#clearColor}.
  44194. *
  44195. * @async
  44196. * @deprecated
  44197. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  44198. */
  44199. async clearColorAsync() {
  44200. warnOnce( 'Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  44201. this.clear( true, false, false );
  44202. }
  44203. /**
  44204. * Async version of {@link Renderer#clearDepth}.
  44205. *
  44206. * @async
  44207. * @deprecated
  44208. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  44209. */
  44210. async clearDepthAsync() {
  44211. warnOnce( 'Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  44212. this.clear( false, true, false );
  44213. }
  44214. /**
  44215. * Async version of {@link Renderer#clearStencil}.
  44216. *
  44217. * @async
  44218. * @deprecated
  44219. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  44220. */
  44221. async clearStencilAsync() {
  44222. warnOnce( 'Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  44223. this.clear( false, false, true );
  44224. }
  44225. /**
  44226. * Returns `true` if a framebuffer target is needed to perform tone mapping or color space conversion.
  44227. * If this is the case, the renderer allocates an internal render target for that purpose.
  44228. *
  44229. */
  44230. get needsFrameBufferTarget() {
  44231. const useToneMapping = this.currentToneMapping !== NoToneMapping;
  44232. const useColorSpace = this.currentColorSpace !== ColorManagement.workingColorSpace;
  44233. return useToneMapping || useColorSpace;
  44234. }
  44235. /**
  44236. * The number of samples used for multi-sample anti-aliasing (MSAA).
  44237. *
  44238. * @type {number}
  44239. * @default 0
  44240. */
  44241. get samples() {
  44242. return this._samples;
  44243. }
  44244. /**
  44245. * The current number of samples used for multi-sample anti-aliasing (MSAA).
  44246. *
  44247. * When rendering to a custom render target, the number of samples of that render target is used.
  44248. * The number of samples is set to 0 when the renderer needs an internal framebuffer target for
  44249. * tone mapping or color space conversion, or when rendering a fullscreen quad to screen.
  44250. *
  44251. * @type {number}
  44252. */
  44253. get currentSamples() {
  44254. let samples = this._samples;
  44255. if ( this._renderTarget !== null ) {
  44256. samples = this._renderTarget.samples;
  44257. } else if ( this.needsFrameBufferTarget || this._currentRenderContext?.fullscreenPass === true ) {
  44258. samples = 0;
  44259. }
  44260. return samples;
  44261. }
  44262. /**
  44263. * The current tone mapping of the renderer. When not producing screen output,
  44264. * the tone mapping is always `NoToneMapping`.
  44265. *
  44266. * @type {number}
  44267. */
  44268. get currentToneMapping() {
  44269. return this.isOutputTarget ? this.toneMapping : NoToneMapping;
  44270. }
  44271. /**
  44272. * The current color space of the renderer. When not producing screen output,
  44273. * the color space is always the working color space.
  44274. *
  44275. * @type {string}
  44276. */
  44277. get currentColorSpace() {
  44278. return this.isOutputTarget ? this.outputColorSpace : ColorManagement.workingColorSpace;
  44279. }
  44280. /**
  44281. * Returns `true` if the rendering settings are set to screen output.
  44282. *
  44283. * @returns {boolean} True if the current render target is the same of output render target or `null`, otherwise false.
  44284. */
  44285. get isOutputTarget() {
  44286. return this._renderTarget === this._outputRenderTarget || this._renderTarget === null;
  44287. }
  44288. /**
  44289. * Frees all internal resources of the renderer. Call this method if the renderer
  44290. * is no longer in use by your app.
  44291. */
  44292. dispose() {
  44293. if ( this._initialized === true ) {
  44294. this.info.dispose();
  44295. this.backend.dispose();
  44296. this._animation.dispose();
  44297. this._objects.dispose();
  44298. this._geometries.dispose();
  44299. this._pipelines.dispose();
  44300. this._nodes.dispose();
  44301. this._bindings.dispose();
  44302. this._renderLists.dispose();
  44303. this._renderContexts.dispose();
  44304. this._textures.dispose();
  44305. for ( const canvasTarget of this._frameBufferTargets.keys() ) {
  44306. canvasTarget.dispose();
  44307. }
  44308. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  44309. if ( queryPool !== null ) queryPool.dispose();
  44310. } );
  44311. }
  44312. this.setRenderTarget( null );
  44313. this.setAnimationLoop( null );
  44314. }
  44315. /**
  44316. * Sets the given render target. Calling this method means the renderer does not
  44317. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  44318. * Use `null` as the first argument to reset the state.
  44319. *
  44320. * @param {?RenderTarget} renderTarget - The render target to set.
  44321. * @param {number} [activeCubeFace=0] - The active cube face.
  44322. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  44323. */
  44324. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  44325. this._renderTarget = renderTarget;
  44326. this._activeCubeFace = activeCubeFace;
  44327. this._activeMipmapLevel = activeMipmapLevel;
  44328. }
  44329. /**
  44330. * Returns the current render target.
  44331. *
  44332. * @return {?RenderTarget} The render target. Returns `null` if no render target is set.
  44333. */
  44334. getRenderTarget() {
  44335. return this._renderTarget;
  44336. }
  44337. /**
  44338. * Sets the output render target for the renderer.
  44339. *
  44340. * @param {?RenderTarget} renderTarget - The render target to set as the output target.
  44341. */
  44342. setOutputRenderTarget( renderTarget ) {
  44343. this._outputRenderTarget = renderTarget;
  44344. }
  44345. /**
  44346. * Returns the current output target.
  44347. *
  44348. * @return {?RenderTarget} The current output render target. Returns `null` if no output target is set.
  44349. */
  44350. getOutputRenderTarget() {
  44351. return this._outputRenderTarget;
  44352. }
  44353. /**
  44354. * Sets the canvas target. The canvas target manages the HTML canvas
  44355. * or the offscreen canvas the renderer draws into.
  44356. *
  44357. * @param {CanvasTarget} canvasTarget - The canvas target.
  44358. */
  44359. setCanvasTarget( canvasTarget ) {
  44360. this._canvasTarget.removeEventListener( 'resize', this._onCanvasTargetResize );
  44361. this._canvasTarget = canvasTarget;
  44362. this._canvasTarget.addEventListener( 'resize', this._onCanvasTargetResize );
  44363. }
  44364. /**
  44365. * Returns the current canvas target.
  44366. *
  44367. * @return {CanvasTarget} The current canvas target.
  44368. */
  44369. getCanvasTarget() {
  44370. return this._canvasTarget;
  44371. }
  44372. /**
  44373. * Resets the renderer to the initial state before WebXR started.
  44374. *
  44375. * @private
  44376. */
  44377. _resetXRState() {
  44378. this.backend.setXRTarget( null );
  44379. this.setOutputRenderTarget( null );
  44380. this.setRenderTarget( null );
  44381. for ( const canvasTarget of this._frameBufferTargets.keys() ) {
  44382. canvasTarget.dispose();
  44383. }
  44384. }
  44385. /**
  44386. * Callback for {@link Renderer#setRenderObjectFunction}.
  44387. *
  44388. * @callback renderObjectFunction
  44389. * @param {Object3D} object - The 3D object.
  44390. * @param {Scene} scene - The scene the 3D object belongs to.
  44391. * @param {Camera} camera - The camera the object should be rendered with.
  44392. * @param {BufferGeometry} geometry - The object's geometry.
  44393. * @param {Material} material - The object's material.
  44394. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  44395. * @param {LightsNode} lightsNode - The current lights node.
  44396. * @param {ClippingContext} clippingContext - The clipping context.
  44397. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  44398. */
  44399. /**
  44400. * Sets the given render object function. Calling this method overwrites the default implementation
  44401. * which is {@link Renderer#renderObject}. Defining a custom function can be useful
  44402. * if you want to modify the way objects are rendered. For example you can define things like "every
  44403. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  44404. * The custom function must always call `renderObject()` in its implementation.
  44405. *
  44406. * Use `null` as the first argument to reset the state.
  44407. *
  44408. * @param {?renderObjectFunction} renderObjectFunction - The render object function.
  44409. */
  44410. setRenderObjectFunction( renderObjectFunction ) {
  44411. this._renderObjectFunction = renderObjectFunction;
  44412. }
  44413. /**
  44414. * Returns the current render object function.
  44415. *
  44416. * @return {?Function} The current render object function. Returns `null` if no function is set.
  44417. */
  44418. getRenderObjectFunction() {
  44419. return this._renderObjectFunction;
  44420. }
  44421. /**
  44422. * Execute a single or an array of compute nodes. This method can only be called
  44423. * if the renderer has been initialized.
  44424. *
  44425. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  44426. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  44427. * - A single number representing count, or
  44428. * - An array [x, y, z] representing dispatch size, or
  44429. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  44430. * @return {Promise|undefined} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  44431. */
  44432. compute( computeNodes, dispatchSize = null ) {
  44433. if ( this._isDeviceLost === true ) return;
  44434. if ( this._initialized === false ) {
  44435. warn( 'Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  44436. return this.computeAsync( computeNodes, dispatchSize );
  44437. }
  44438. //
  44439. const nodeFrame = this._nodes.nodeFrame;
  44440. const previousRenderId = nodeFrame.renderId;
  44441. //
  44442. this.info.calls ++;
  44443. this.info.compute.calls ++;
  44444. this.info.compute.frameCalls ++;
  44445. nodeFrame.renderId = this.info.calls;
  44446. //
  44447. this.backend.updateTimeStampUID( computeNodes );
  44448. this.inspector.beginCompute( this.backend.getTimestampUID( computeNodes ), computeNodes );
  44449. //
  44450. const backend = this.backend;
  44451. const pipelines = this._pipelines;
  44452. const bindings = this._bindings;
  44453. const nodes = this._nodes;
  44454. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  44455. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  44456. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  44457. }
  44458. backend.beginCompute( computeNodes );
  44459. for ( const computeNode of computeList ) {
  44460. // onInit
  44461. if ( pipelines.has( computeNode ) === false ) {
  44462. const dispose = () => {
  44463. computeNode.removeEventListener( 'dispose', dispose );
  44464. pipelines.delete( computeNode );
  44465. bindings.deleteForCompute( computeNode );
  44466. nodes.delete( computeNode );
  44467. };
  44468. computeNode.addEventListener( 'dispose', dispose );
  44469. //
  44470. const onInitFn = computeNode.onInitFunction;
  44471. if ( onInitFn !== null ) {
  44472. onInitFn.call( computeNode, { renderer: this } );
  44473. }
  44474. }
  44475. nodes.updateForCompute( computeNode );
  44476. bindings.updateForCompute( computeNode );
  44477. const computeBindings = bindings.getForCompute( computeNode );
  44478. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  44479. backend.compute( computeNodes, computeNode, computeBindings, computePipeline, dispatchSize );
  44480. }
  44481. backend.finishCompute( computeNodes );
  44482. //
  44483. nodeFrame.renderId = previousRenderId;
  44484. //
  44485. this.inspector.finishCompute( this.backend.getTimestampUID( computeNodes ) );
  44486. }
  44487. /**
  44488. * Execute a single or an array of compute nodes.
  44489. *
  44490. * @async
  44491. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  44492. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  44493. * - A single number representing count, or
  44494. * - An array [x, y, z] representing dispatch size, or
  44495. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  44496. * @return {Promise} A Promise that resolve when the compute has finished.
  44497. */
  44498. async computeAsync( computeNodes, dispatchSize = null ) {
  44499. if ( this._initialized === false ) await this.init();
  44500. this.compute( computeNodes, dispatchSize );
  44501. }
  44502. /**
  44503. * Checks if the given feature is supported by the selected backend.
  44504. *
  44505. * @async
  44506. * @deprecated
  44507. * @param {string} name - The feature's name.
  44508. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  44509. */
  44510. async hasFeatureAsync( name ) {
  44511. warnOnce( 'Renderer: "hasFeatureAsync()" has been deprecated. Use "hasFeature()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  44512. await this.init();
  44513. return this.hasFeature( name );
  44514. }
  44515. async resolveTimestampsAsync( type = 'render' ) {
  44516. if ( this._initialized === false ) await this.init();
  44517. return this.backend.resolveTimestampsAsync( type );
  44518. }
  44519. /**
  44520. * Checks if the given feature is supported by the selected backend. If the
  44521. * renderer has not been initialized, this method always returns `false`.
  44522. *
  44523. * @param {string} name - The feature's name.
  44524. * @return {boolean} Whether the feature is supported or not.
  44525. */
  44526. hasFeature( name ) {
  44527. if ( this._initialized === false ) {
  44528. throw new Error( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before using this method.' );
  44529. }
  44530. return this.backend.hasFeature( name );
  44531. }
  44532. /**
  44533. * Returns `true` when the renderer has been initialized.
  44534. *
  44535. * @return {boolean} Whether the renderer has been initialized or not.
  44536. */
  44537. hasInitialized() {
  44538. return this._initialized;
  44539. }
  44540. /**
  44541. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  44542. * (which can cause noticeable lags due to decode and GPU upload overhead).
  44543. *
  44544. * @async
  44545. * @deprecated
  44546. * @param {Texture} texture - The texture.
  44547. * @return {Promise} A Promise that resolves when the texture has been initialized.
  44548. */
  44549. async initTextureAsync( texture ) {
  44550. warnOnce( 'Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  44551. await this.init();
  44552. this.initTexture( texture );
  44553. }
  44554. /**
  44555. * Initializes the given texture. Useful for preloading a texture rather than waiting until first render
  44556. * (which can cause noticeable lags due to decode and GPU upload overhead).
  44557. *
  44558. * This method can only be used if the renderer has been initialized.
  44559. *
  44560. * @param {Texture} texture - The texture.
  44561. */
  44562. initTexture( texture ) {
  44563. if ( this._initialized === false ) {
  44564. throw new Error( 'THREE.Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before using this method.' );
  44565. }
  44566. this._textures.updateTexture( texture );
  44567. }
  44568. /**
  44569. * Initializes the given render target.
  44570. *
  44571. * @param {RenderTarget} renderTarget - The render target to intialize.
  44572. */
  44573. initRenderTarget( renderTarget ) {
  44574. if ( this._initialized === false ) {
  44575. throw new Error( 'THREE.Renderer: .initRenderTarget() called before the backend is initialized. Use "await renderer.init();" before using this method.' );
  44576. }
  44577. this._textures.updateRenderTarget( renderTarget );
  44578. const renderTargetData = this._textures.get( renderTarget );
  44579. const renderContext = this._renderContexts.get( renderTarget );
  44580. renderContext.textures = renderTargetData.textures;
  44581. renderContext.depthTexture = renderTargetData.depthTexture;
  44582. renderContext.width = renderTargetData.width;
  44583. renderContext.height = renderTargetData.height;
  44584. renderContext.renderTarget = renderTarget;
  44585. renderContext.depth = renderTarget.depthBuffer;
  44586. renderContext.stencil = renderTarget.stencilBuffer;
  44587. this.backend.initRenderTarget( renderContext );
  44588. }
  44589. /**
  44590. * Copies the current bound framebuffer into the given texture.
  44591. *
  44592. * @param {FramebufferTexture} framebufferTexture - The texture.
  44593. * @param {?(Vector2|Vector4)} [rectangle=null] - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  44594. */
  44595. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  44596. if ( rectangle !== null ) {
  44597. if ( rectangle.isVector2 ) {
  44598. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  44599. } else if ( rectangle.isVector4 ) {
  44600. rectangle = _vector4.copy( rectangle ).floor();
  44601. } else {
  44602. error( 'Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  44603. return;
  44604. }
  44605. } else {
  44606. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  44607. }
  44608. //
  44609. let renderContext = this._currentRenderContext;
  44610. let renderTarget;
  44611. if ( renderContext !== null ) {
  44612. renderTarget = renderContext.renderTarget;
  44613. } else {
  44614. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  44615. if ( renderTarget !== null ) {
  44616. this._textures.updateRenderTarget( renderTarget );
  44617. renderContext = this._textures.get( renderTarget );
  44618. }
  44619. }
  44620. //
  44621. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  44622. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  44623. this._inspector.copyFramebufferToTexture( framebufferTexture );
  44624. }
  44625. /**
  44626. * Copies data of the given source texture into a destination texture.
  44627. *
  44628. * @param {Texture} srcTexture - The source texture.
  44629. * @param {Texture} dstTexture - The destination texture.
  44630. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  44631. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  44632. * @param {number} [srcLevel=0] - The source mip level to copy from.
  44633. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  44634. */
  44635. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  44636. this._textures.updateTexture( srcTexture );
  44637. this._textures.updateTexture( dstTexture );
  44638. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  44639. this._inspector.copyTextureToTexture( srcTexture, dstTexture );
  44640. }
  44641. /**
  44642. * Reads pixel data from the given render target.
  44643. *
  44644. * @async
  44645. * @param {RenderTarget} renderTarget - The render target to read from.
  44646. * @param {number} x - The `x` coordinate of the copy region's origin.
  44647. * @param {number} y - The `y` coordinate of the copy region's origin.
  44648. * @param {number} width - The width of the copy region.
  44649. * @param {number} height - The height of the copy region.
  44650. * @param {number} [textureIndex=0] - The texture index of a MRT render target.
  44651. * @param {number} [faceIndex=0] - The active cube face index.
  44652. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  44653. */
  44654. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  44655. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  44656. }
  44657. /**
  44658. * Analyzes the given 3D object's hierarchy and builds render lists from the
  44659. * processed hierarchy.
  44660. *
  44661. * @private
  44662. * @param {Object3D} object - The 3D object to process (usually a scene).
  44663. * @param {Camera} camera - The camera the object is rendered with.
  44664. * @param {number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  44665. * @param {RenderList} renderList - The current render list.
  44666. * @param {ClippingContext} clippingContext - The current clipping context.
  44667. */
  44668. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  44669. if ( object.visible === false ) return;
  44670. const visible = object.layers.test( camera.layers );
  44671. if ( visible ) {
  44672. if ( object.isGroup ) {
  44673. groupOrder = object.renderOrder;
  44674. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  44675. } else if ( object.isLOD ) {
  44676. if ( object.autoUpdate === true ) object.update( camera );
  44677. } else if ( object.isLight ) {
  44678. renderList.pushLight( object );
  44679. } else if ( object.isSprite ) {
  44680. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  44681. if ( ! object.frustumCulled || frustum.intersectsSprite( object ) ) {
  44682. if ( this.sortObjects === true ) {
  44683. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  44684. }
  44685. const { geometry, material } = object;
  44686. if ( material.visible ) {
  44687. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  44688. }
  44689. }
  44690. } else if ( object.isLineLoop ) {
  44691. error( 'Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  44692. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  44693. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  44694. if ( ! object.frustumCulled || frustum.intersectsObject( object ) ) {
  44695. const { geometry, material } = object;
  44696. if ( this.sortObjects === true ) {
  44697. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  44698. _vector4
  44699. .copy( geometry.boundingSphere.center )
  44700. .applyMatrix4( object.matrixWorld )
  44701. .applyMatrix4( _projScreenMatrix );
  44702. }
  44703. if ( Array.isArray( material ) ) {
  44704. const groups = geometry.groups;
  44705. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  44706. const group = groups[ i ];
  44707. const groupMaterial = material[ group.materialIndex ];
  44708. if ( groupMaterial && groupMaterial.visible ) {
  44709. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  44710. }
  44711. }
  44712. } else if ( material.visible ) {
  44713. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  44714. }
  44715. }
  44716. }
  44717. }
  44718. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  44719. const baseRenderList = renderList;
  44720. // replace render list
  44721. renderList = this._renderLists.get( object, camera );
  44722. const renderBundle = this._bundles.get( object, camera, this._currentRenderContext );
  44723. const renderBundleData = this.backend.get( renderBundle );
  44724. const renderBundleNeedsUpdate = this._bundleNeedsUpdate( object, renderBundleData );
  44725. if ( renderBundleNeedsUpdate ) {
  44726. // update render list if necessary
  44727. renderList.begin();
  44728. if ( renderBundleData.renderObjects === undefined ) {
  44729. renderBundleData.renderObjects = [];
  44730. } else {
  44731. renderBundleData.renderObjects.length = 0;
  44732. }
  44733. const children = object.children;
  44734. for ( let i = 0, l = children.length; i < l; i ++ ) {
  44735. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  44736. }
  44737. renderList.finish();
  44738. }
  44739. baseRenderList.pushBundle( {
  44740. bundleGroup: object,
  44741. camera,
  44742. renderList,
  44743. } );
  44744. return;
  44745. }
  44746. //
  44747. const children = object.children;
  44748. for ( let i = 0, l = children.length; i < l; i ++ ) {
  44749. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  44750. }
  44751. }
  44752. /**
  44753. * Renders the given render bundles.
  44754. *
  44755. * @private
  44756. * @param {Array<Object>} bundles - Array with render bundle data.
  44757. * @param {Scene} sceneRef - The scene the render bundles belong to.
  44758. * @param {LightsNode} lightsNode - The current lights node.
  44759. */
  44760. _renderBundles( bundles, sceneRef, lightsNode ) {
  44761. for ( const bundle of bundles ) {
  44762. this._renderBundle( bundle, sceneRef, lightsNode );
  44763. }
  44764. }
  44765. /**
  44766. * Renders the transparent objects from the given render lists.
  44767. *
  44768. * @private
  44769. * @param {Array<Object>} renderList - The transparent render list.
  44770. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  44771. * @param {Camera} camera - The camera the render list should be rendered with.
  44772. * @param {Scene} scene - The scene the render list belongs to.
  44773. * @param {LightsNode} lightsNode - The current lights node.
  44774. */
  44775. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  44776. if ( doublePassList.length > 0 ) {
  44777. // render back side
  44778. for ( const { material } of doublePassList ) {
  44779. material.side = BackSide;
  44780. }
  44781. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  44782. // render front side
  44783. for ( const { material } of doublePassList ) {
  44784. material.side = FrontSide;
  44785. }
  44786. this._renderObjects( renderList, camera, scene, lightsNode );
  44787. // restore
  44788. for ( const { material } of doublePassList ) {
  44789. material.side = DoubleSide;
  44790. }
  44791. } else {
  44792. this._renderObjects( renderList, camera, scene, lightsNode );
  44793. }
  44794. }
  44795. /**
  44796. * Renders the objects from the given render list.
  44797. *
  44798. * @private
  44799. * @param {Array<Object>} renderList - The render list.
  44800. * @param {Camera} camera - The camera the render list should be rendered with.
  44801. * @param {Scene} scene - The scene the render list belongs to.
  44802. * @param {LightsNode} lightsNode - The current lights node.
  44803. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  44804. */
  44805. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  44806. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  44807. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  44808. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  44809. }
  44810. }
  44811. /**
  44812. * Retrieves shadow nodes for the given material. This is used to setup shadow passes.
  44813. * The result is cached per material and updated when the material's version changes.
  44814. *
  44815. * @private
  44816. * @param {Material} material
  44817. * @returns {Object} - The shadow nodes for the material.
  44818. */
  44819. _getShadowNodes( material ) {
  44820. const version = material.version;
  44821. let cache = this._cacheShadowNodes.get( material );
  44822. if ( cache === undefined || cache.version !== version ) {
  44823. const hasMap = material.map && material.map.isTexture;
  44824. const hasColorNode = material.colorNode && material.colorNode.isNode;
  44825. const hasCastShadowNode = material.castShadowNode && material.castShadowNode.isNode;
  44826. const hasMaskNode = ( material.maskShadowNode && material.maskShadowNode.isNode ) || ( material.maskNode && material.maskNode.isNode );
  44827. let positionNode = null;
  44828. let colorNode = null;
  44829. let depthNode = null;
  44830. if ( hasMap || hasColorNode || hasCastShadowNode || hasMaskNode ) {
  44831. let shadowRGB;
  44832. let shadowAlpha;
  44833. if ( hasCastShadowNode ) {
  44834. shadowRGB = material.castShadowNode.rgb;
  44835. shadowAlpha = material.castShadowNode.a;
  44836. if ( this.shadowMap.transmitted !== true ) {
  44837. warnOnce( 'Renderer: `shadowMap.transmitted` needs to be set to `true` when using `material.castShadowNode`.' );
  44838. }
  44839. } else {
  44840. shadowRGB = vec3( 0 );
  44841. shadowAlpha = float( 1 );
  44842. }
  44843. if ( hasMap ) {
  44844. shadowAlpha = shadowAlpha.mul( reference( 'map', 'texture', material ).a );
  44845. }
  44846. if ( hasColorNode ) {
  44847. shadowAlpha = shadowAlpha.mul( material.colorNode.a );
  44848. }
  44849. colorNode = vec4( shadowRGB, shadowAlpha );
  44850. if ( hasMaskNode ) {
  44851. const maskNode = material.maskShadowNode || material.maskNode;
  44852. colorNode = Fn( ( [ color ] ) => {
  44853. maskNode.not().discard();
  44854. return color;
  44855. } )( colorNode );
  44856. }
  44857. }
  44858. if ( material.depthNode && material.depthNode.isNode ) {
  44859. depthNode = material.depthNode;
  44860. }
  44861. if ( material.castShadowPositionNode && material.castShadowPositionNode.isNode ) {
  44862. positionNode = material.castShadowPositionNode;
  44863. } else if ( material.positionNode && material.positionNode.isNode ) {
  44864. positionNode = material.positionNode;
  44865. }
  44866. cache = {
  44867. version,
  44868. colorNode,
  44869. depthNode,
  44870. positionNode
  44871. };
  44872. this._cacheShadowNodes.set( material, cache );
  44873. }
  44874. return cache;
  44875. }
  44876. /**
  44877. * Updates the camera so it's prepared for rendering operations.
  44878. *
  44879. * @private
  44880. * @param {Camera} camera - The camera to update.
  44881. * @return {Camera} The returned camera might be different depending on whether XR is used or not.
  44882. */
  44883. _updateCamera( camera ) {
  44884. const xr = this.xr;
  44885. if ( xr.isPresenting === false ) {
  44886. let projectionMatrixNeedsUpdate = false;
  44887. // reversed depth
  44888. if ( this.reversedDepthBuffer === true && camera.reversedDepth !== true ) {
  44889. camera._reversedDepth = true;
  44890. if ( camera.isArrayCamera ) {
  44891. for ( const subCamera of camera.cameras ) {
  44892. subCamera._reversedDepth = true;
  44893. }
  44894. }
  44895. projectionMatrixNeedsUpdate = true;
  44896. }
  44897. // WebGPU/WebGL coordinate system
  44898. const coordinateSystem = this.coordinateSystem;
  44899. if ( camera.coordinateSystem !== coordinateSystem ) {
  44900. camera.coordinateSystem = coordinateSystem;
  44901. if ( camera.isArrayCamera ) {
  44902. for ( const subCamera of camera.cameras ) {
  44903. subCamera.coordinateSystem = coordinateSystem;
  44904. }
  44905. }
  44906. projectionMatrixNeedsUpdate = true;
  44907. }
  44908. // camera update
  44909. if ( projectionMatrixNeedsUpdate === true ) {
  44910. camera.updateProjectionMatrix();
  44911. if ( camera.isArrayCamera ) {
  44912. for ( const subCamera of camera.cameras ) {
  44913. subCamera.updateProjectionMatrix();
  44914. }
  44915. }
  44916. }
  44917. }
  44918. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  44919. // handle XR
  44920. if ( xr.enabled === true && xr.isPresenting === true ) {
  44921. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  44922. camera = xr.getCamera(); // use XR camera for rendering
  44923. }
  44924. return camera;
  44925. }
  44926. /**
  44927. * This method represents the default render object function that manages the render lifecycle
  44928. * of the object.
  44929. *
  44930. * @param {Object3D} object - The 3D object.
  44931. * @param {Scene} scene - The scene the 3D object belongs to.
  44932. * @param {Camera} camera - The camera the object should be rendered with.
  44933. * @param {BufferGeometry} geometry - The object's geometry.
  44934. * @param {Material} material - The object's material.
  44935. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  44936. * @param {LightsNode} lightsNode - The current lights node.
  44937. * @param {?ClippingContext} clippingContext - The clipping context.
  44938. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  44939. */
  44940. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  44941. let materialOverride = false;
  44942. let materialColorNode;
  44943. let materialDepthNode;
  44944. let materialPositionNode;
  44945. let materialSide;
  44946. let materialDisplacementMap;
  44947. let materialDisplacementScale;
  44948. let materialDisplacementBias;
  44949. const previousSourceMaterial = this._currentSourceMaterial;
  44950. //
  44951. object.onBeforeRender( this, scene, camera, geometry, material, group );
  44952. //
  44953. if ( material.allowOverride === true && scene.overrideMaterial !== null ) {
  44954. this._currentSourceMaterial = material;
  44955. const overrideMaterial = scene.overrideMaterial;
  44956. materialOverride = true;
  44957. // store original nodes
  44958. materialColorNode = ( overrideMaterial.isNodeMaterial ) ? overrideMaterial.colorNode : null;
  44959. materialDepthNode = ( overrideMaterial.isNodeMaterial ) ? overrideMaterial.depthNode : null;
  44960. materialPositionNode = ( overrideMaterial.isNodeMaterial ) ? overrideMaterial.positionNode : null;
  44961. materialSide = scene.overrideMaterial.side;
  44962. materialDisplacementMap = overrideMaterial.displacementMap;
  44963. materialDisplacementScale = overrideMaterial.displacementScale;
  44964. materialDisplacementBias = overrideMaterial.displacementBias;
  44965. if ( material.positionNode && material.positionNode.isNode ) {
  44966. overrideMaterial.positionNode = material.positionNode;
  44967. }
  44968. overrideMaterial.alphaTest = material.alphaTest;
  44969. overrideMaterial.alphaMap = material.alphaMap;
  44970. overrideMaterial.displacementMap = material.displacementMap;
  44971. overrideMaterial.displacementScale = material.displacementScale;
  44972. overrideMaterial.displacementBias = material.displacementBias;
  44973. overrideMaterial.transparent = material.transparent || material.transmission > 0 ||
  44974. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  44975. ( material.backdropNode && material.backdropNode.isNode );
  44976. if ( overrideMaterial.isShadowPassMaterial ) {
  44977. const { colorNode, depthNode, positionNode } = this._getShadowNodes( material );
  44978. if ( this.shadowMap.type === VSMShadowMap ) {
  44979. overrideMaterial.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  44980. } else {
  44981. overrideMaterial.side = ( material.shadowSide !== null ) ? material.shadowSide : _shadowSide[ material.side ];
  44982. }
  44983. if ( colorNode !== null ) overrideMaterial.colorNode = colorNode;
  44984. if ( depthNode !== null ) overrideMaterial.depthNode = depthNode;
  44985. if ( positionNode !== null ) overrideMaterial.positionNode = positionNode;
  44986. }
  44987. material = overrideMaterial;
  44988. }
  44989. //
  44990. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  44991. material.side = BackSide;
  44992. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  44993. material.side = FrontSide;
  44994. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  44995. material.side = DoubleSide;
  44996. } else {
  44997. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  44998. }
  44999. //
  45000. if ( materialOverride ) {
  45001. scene.overrideMaterial.colorNode = materialColorNode;
  45002. scene.overrideMaterial.depthNode = materialDepthNode;
  45003. scene.overrideMaterial.positionNode = materialPositionNode;
  45004. scene.overrideMaterial.side = materialSide;
  45005. scene.overrideMaterial.displacementMap = materialDisplacementMap;
  45006. scene.overrideMaterial.displacementScale = materialDisplacementScale;
  45007. scene.overrideMaterial.displacementBias = materialDisplacementBias;
  45008. }
  45009. this._currentSourceMaterial = previousSourceMaterial;
  45010. //
  45011. object.onAfterRender( this, scene, camera, geometry, material, group );
  45012. }
  45013. /**
  45014. * Checks if the given compatibility is supported by the selected backend.
  45015. *
  45016. * @param {string} name - The compatibility's name.
  45017. * @return {boolean} Whether the compatibility is supported or not.
  45018. */
  45019. hasCompatibility( name ) {
  45020. if ( this._initialized === false ) {
  45021. throw new Error( 'THREE.Renderer: .hasCompatibility() called before the backend is initialized. Use "await renderer.init();" before using this method.' );
  45022. }
  45023. return this.backend.hasCompatibility( name );
  45024. }
  45025. /**
  45026. * This method represents the default `_handleObjectFunction` implementation which creates
  45027. * a render object from the given data and performs the draw command with the selected backend.
  45028. *
  45029. * @private
  45030. * @param {Object3D} object - The 3D object.
  45031. * @param {Material} material - The object's material.
  45032. * @param {Scene} scene - The scene the 3D object belongs to.
  45033. * @param {Camera} camera - The camera the object should be rendered with.
  45034. * @param {LightsNode} lightsNode - The current lights node.
  45035. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  45036. * @param {ClippingContext} clippingContext - The clipping context.
  45037. * @param {string} [passId] - An optional ID for identifying the pass.
  45038. */
  45039. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  45040. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  45041. renderObject.drawRange = object.geometry.drawRange;
  45042. renderObject.group = group;
  45043. if ( this._currentRenderBundle !== null ) {
  45044. const renderBundleData = this.backend.get( this._currentRenderBundle );
  45045. renderBundleData.renderObjects.push( renderObject );
  45046. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  45047. }
  45048. //
  45049. const needsRefresh = this._nodes.needsRefresh( renderObject );
  45050. if ( needsRefresh ) {
  45051. this._nodes.updateBefore( renderObject );
  45052. this._geometries.updateForRender( renderObject );
  45053. this._nodes.updateForRender( renderObject );
  45054. this._bindings.updateForRender( renderObject );
  45055. }
  45056. this._pipelines.updateForRender( renderObject );
  45057. //
  45058. if ( this._pipelines.isReady( renderObject ) ) {
  45059. this.backend.draw( renderObject, this.info );
  45060. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  45061. }
  45062. }
  45063. /**
  45064. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  45065. * Used in `compileAsync()`.
  45066. *
  45067. * @private
  45068. * @param {Object3D} object - The 3D object.
  45069. * @param {Material} material - The object's material.
  45070. * @param {Scene} scene - The scene the 3D object belongs to.
  45071. * @param {Camera} camera - The camera the object should be rendered with.
  45072. * @param {LightsNode} lightsNode - The current lights node.
  45073. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  45074. * @param {ClippingContext} clippingContext - The clipping context.
  45075. * @param {string} [passId] - An optional ID for identifying the pass.
  45076. */
  45077. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  45078. // If in async compilation mode, queue the work for sequential execution
  45079. if ( this._compilationPromises !== null ) {
  45080. // Store work items instead of promises - will be processed sequentially
  45081. this._compilationPromises.push( {
  45082. object,
  45083. material,
  45084. scene,
  45085. camera,
  45086. lightsNode,
  45087. group,
  45088. clippingContext,
  45089. passId,
  45090. renderContext: this._currentRenderContext
  45091. } );
  45092. return;
  45093. }
  45094. // Sync path
  45095. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  45096. renderObject.drawRange = object.geometry.drawRange;
  45097. renderObject.group = group;
  45098. //
  45099. this._nodes.updateBefore( renderObject );
  45100. this._geometries.updateForRender( renderObject );
  45101. this._nodes.updateForRender( renderObject );
  45102. this._bindings.updateForRender( renderObject );
  45103. this._pipelines.getForRender( renderObject, this._compilationPromises );
  45104. this._nodes.updateAfter( renderObject );
  45105. }
  45106. /**
  45107. * Callback when the canvas has been resized.
  45108. *
  45109. * @private
  45110. */
  45111. _onCanvasTargetResize() {
  45112. if ( this._initialized ) this.backend.updateSize();
  45113. }
  45114. /**
  45115. * Alias for `compileAsync()`.
  45116. *
  45117. * @method
  45118. * @param {Object3D} scene - The scene or 3D object to precompile.
  45119. * @param {Camera} camera - The camera that is used to render the scene.
  45120. * @param {Scene} targetScene - If the first argument is a 3D object, this parameter must represent the scene the 3D object is going to be added.
  45121. * @return {function(Object3D, Camera, ?Scene): Promise|undefined} A Promise that resolves when the compile has been finished.
  45122. */
  45123. get compile() {
  45124. return this.compileAsync;
  45125. }
  45126. }
  45127. /**
  45128. * A binding represents the connection between a resource (like a texture, sampler
  45129. * or uniform buffer) and the resource definition in a shader stage.
  45130. *
  45131. * This module is an abstract base class for all concrete bindings types.
  45132. *
  45133. * @abstract
  45134. * @private
  45135. */
  45136. class Binding {
  45137. /**
  45138. * Constructs a new binding.
  45139. *
  45140. * @param {string} [name=''] - The binding's name.
  45141. */
  45142. constructor( name = '' ) {
  45143. /**
  45144. * The binding's name.
  45145. *
  45146. * @type {string}
  45147. */
  45148. this.name = name;
  45149. /**
  45150. * A bitmask that defines in what shader stages the
  45151. * binding's resource is accessible.
  45152. *
  45153. * @type {number}
  45154. */
  45155. this.visibility = 0;
  45156. }
  45157. /**
  45158. * Makes sure binding's resource is visible for the given shader stage.
  45159. *
  45160. * @param {number} visibility - The shader stage.
  45161. */
  45162. setVisibility( visibility ) {
  45163. this.visibility |= visibility;
  45164. }
  45165. /**
  45166. * The shader stages in which the binding's resource is visible.
  45167. *
  45168. * @return {number} The visibility bitmask.
  45169. */
  45170. getVisibility() {
  45171. return this.visibility;
  45172. }
  45173. /**
  45174. * Clones the binding.
  45175. *
  45176. * @return {Binding} The cloned binding.
  45177. */
  45178. clone() {
  45179. return Object.assign( new this.constructor(), this );
  45180. }
  45181. }
  45182. /**
  45183. * This function is usually called with the length in bytes of an array buffer.
  45184. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  45185. *
  45186. * @function
  45187. * @param {number} floatLength - The buffer length.
  45188. * @return {number} The padded length.
  45189. */
  45190. function getFloatLength( floatLength ) {
  45191. // ensure chunk size alignment (STD140 layout)
  45192. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  45193. }
  45194. /**
  45195. * Represents a buffer binding type.
  45196. *
  45197. * @private
  45198. * @abstract
  45199. * @augments Binding
  45200. */
  45201. class Buffer extends Binding {
  45202. /**
  45203. * Constructs a new buffer.
  45204. *
  45205. * @param {string} name - The buffer's name.
  45206. * @param {TypedArray} [buffer=null] - The buffer.
  45207. */
  45208. constructor( name, buffer = null ) {
  45209. super( name );
  45210. /**
  45211. * This flag can be used for type testing.
  45212. *
  45213. * @type {boolean}
  45214. * @readonly
  45215. * @default true
  45216. */
  45217. this.isBuffer = true;
  45218. /**
  45219. * The bytes per element.
  45220. *
  45221. * @type {number}
  45222. */
  45223. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  45224. /**
  45225. * A reference to the internal buffer.
  45226. *
  45227. * @private
  45228. * @type {TypedArray}
  45229. */
  45230. this._buffer = buffer;
  45231. /**
  45232. * An array of update ranges.
  45233. *
  45234. * @private
  45235. * @type {Array<{start: number, count: number}>}
  45236. */
  45237. this._updateRanges = [];
  45238. }
  45239. /**
  45240. * The array of update ranges.
  45241. *
  45242. * @type {Array<{start: number, count: number}>}
  45243. */
  45244. get updateRanges() {
  45245. return this._updateRanges;
  45246. }
  45247. /**
  45248. * Adds an update range.
  45249. *
  45250. * @param {number} start - The start index.
  45251. * @param {number} count - The number of elements.
  45252. */
  45253. addUpdateRange( start, count ) {
  45254. this.updateRanges.push( { start, count } );
  45255. }
  45256. /**
  45257. * Clears all update ranges.
  45258. */
  45259. clearUpdateRanges() {
  45260. this.updateRanges.length = 0;
  45261. }
  45262. /**
  45263. * The buffer's byte length.
  45264. *
  45265. * @type {number}
  45266. * @readonly
  45267. */
  45268. get byteLength() {
  45269. return getFloatLength( this._buffer.byteLength );
  45270. }
  45271. /**
  45272. * A reference to the internal buffer.
  45273. *
  45274. * @type {Float32Array}
  45275. * @readonly
  45276. */
  45277. get buffer() {
  45278. return this._buffer;
  45279. }
  45280. /**
  45281. * Updates the binding.
  45282. *
  45283. * @return {boolean} Whether the buffer has been updated and must be
  45284. * uploaded to the GPU.
  45285. */
  45286. update() {
  45287. return true;
  45288. }
  45289. /**
  45290. * Releases the buffer.
  45291. */
  45292. release() {
  45293. this._buffer = null;
  45294. }
  45295. }
  45296. /**
  45297. * Represents a uniform buffer binding type.
  45298. *
  45299. * @private
  45300. * @augments Buffer
  45301. */
  45302. class UniformBuffer extends Buffer {
  45303. /**
  45304. * Constructs a new uniform buffer.
  45305. *
  45306. * @param {string} name - The buffer's name.
  45307. * @param {TypedArray} [buffer=null] - The buffer.
  45308. */
  45309. constructor( name, buffer = null ) {
  45310. super( name, buffer );
  45311. /**
  45312. * This flag can be used for type testing.
  45313. *
  45314. * @type {boolean}
  45315. * @readonly
  45316. * @default true
  45317. */
  45318. this.isUniformBuffer = true;
  45319. }
  45320. }
  45321. let _id$4 = 0;
  45322. /**
  45323. * A special form of uniform buffer binding type.
  45324. * It's buffer value is managed by a node object.
  45325. *
  45326. * @private
  45327. * @augments UniformBuffer
  45328. */
  45329. class NodeUniformBuffer extends UniformBuffer {
  45330. /**
  45331. * Constructs a new node-based uniform buffer.
  45332. *
  45333. * @param {BufferNode} nodeUniform - The uniform buffer node.
  45334. * @param {UniformGroupNode} groupNode - The uniform group node.
  45335. */
  45336. constructor( nodeUniform, groupNode ) {
  45337. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  45338. /**
  45339. * The uniform buffer node.
  45340. *
  45341. * @type {BufferNode}
  45342. */
  45343. this.nodeUniform = nodeUniform;
  45344. /**
  45345. * The uniform group node.
  45346. *
  45347. * @type {UniformGroupNode}
  45348. */
  45349. this.groupNode = groupNode;
  45350. /**
  45351. * This flag can be used for type testing.
  45352. *
  45353. * @type {boolean}
  45354. * @readonly
  45355. * @default true
  45356. */
  45357. this.isNodeUniformBuffer = true;
  45358. }
  45359. /**
  45360. * The array of update ranges.
  45361. *
  45362. * @param {Array<{start: number, count: number}>} value - The update ranges.
  45363. */
  45364. set updateRanges( value ) {
  45365. this.nodeUniform.updateRanges = value;
  45366. }
  45367. /**
  45368. * The array of update ranges.
  45369. *
  45370. * @type {Array<{start: number, count: number}>}
  45371. */
  45372. get updateRanges() {
  45373. return this.nodeUniform.updateRanges;
  45374. }
  45375. /**
  45376. * Adds a range of data in the data array to be updated on the GPU.
  45377. *
  45378. * @param {number} start - Position at which to start update.
  45379. * @param {number} count - The number of components to update.
  45380. */
  45381. addUpdateRange( start, count ) {
  45382. this.nodeUniform.addUpdateRange( start, count );
  45383. }
  45384. /**
  45385. * Clears all update ranges.
  45386. */
  45387. clearUpdateRanges() {
  45388. this.nodeUniform.clearUpdateRanges();
  45389. }
  45390. /**
  45391. * The buffer's byte length.
  45392. *
  45393. * @type {number}
  45394. * @readonly
  45395. */
  45396. get byteLength() {
  45397. return getFloatLength( this.buffer.byteLength );
  45398. }
  45399. /**
  45400. * The uniform buffer.
  45401. *
  45402. * @type {Float32Array}
  45403. */
  45404. get buffer() {
  45405. return this.nodeUniform.value;
  45406. }
  45407. }
  45408. /**
  45409. * This class represents a uniform buffer binding but with
  45410. * an API that allows to maintain individual uniform objects.
  45411. *
  45412. * @private
  45413. * @augments UniformBuffer
  45414. */
  45415. class UniformsGroup extends UniformBuffer {
  45416. /**
  45417. * Constructs a new uniforms group.
  45418. *
  45419. * @param {string} name - The group's name.
  45420. */
  45421. constructor( name ) {
  45422. super( name );
  45423. /**
  45424. * This flag can be used for type testing.
  45425. *
  45426. * @type {boolean}
  45427. * @readonly
  45428. * @default true
  45429. */
  45430. this.isUniformsGroup = true;
  45431. /**
  45432. * An array with the raw uniform values.
  45433. *
  45434. * @private
  45435. * @type {?Array<number>}
  45436. * @default null
  45437. */
  45438. this._values = null;
  45439. /**
  45440. * An array of uniform objects.
  45441. *
  45442. * The order of uniforms in this array must match the order of uniforms in the shader.
  45443. *
  45444. * @type {Array<Uniform>}
  45445. */
  45446. this.uniforms = [];
  45447. /**
  45448. * A cache for the uniform update ranges.
  45449. *
  45450. * @private
  45451. * @type {Map<number, {start: number, count: number}>}
  45452. */
  45453. this._updateRangeCache = new Map();
  45454. /**
  45455. * Uniform indices whose range has already been pushed into `updateRanges`
  45456. * during the current update cycle. Reset on `clearUpdateRanges()`.
  45457. *
  45458. * @private
  45459. * @type {Set<number>}
  45460. */
  45461. this._addedIndices = new Set();
  45462. }
  45463. /**
  45464. * Adds a uniform's update range to this buffer.
  45465. *
  45466. * @param {Uniform} uniform - The uniform.
  45467. */
  45468. addUniformUpdateRange( uniform ) {
  45469. const index = uniform.index;
  45470. if ( this._addedIndices.has( index ) ) return;
  45471. let range = this._updateRangeCache.get( index );
  45472. if ( range === undefined ) {
  45473. range = { start: 0, count: 0 };
  45474. this._updateRangeCache.set( index, range );
  45475. }
  45476. range.start = uniform.offset;
  45477. range.count = uniform.itemSize;
  45478. this._addedIndices.add( index );
  45479. this.updateRanges.push( range );
  45480. }
  45481. /**
  45482. * Clears all update ranges of this buffer.
  45483. */
  45484. clearUpdateRanges() {
  45485. this._addedIndices.clear();
  45486. super.clearUpdateRanges();
  45487. }
  45488. /**
  45489. * Adds a uniform to this group.
  45490. *
  45491. * @param {Uniform} uniform - The uniform to add.
  45492. * @return {UniformsGroup} A reference to this group.
  45493. */
  45494. addUniform( uniform ) {
  45495. this.uniforms.push( uniform );
  45496. return this;
  45497. }
  45498. /**
  45499. * Removes a uniform from this group.
  45500. *
  45501. * @param {Uniform} uniform - The uniform to remove.
  45502. * @return {UniformsGroup} A reference to this group.
  45503. */
  45504. removeUniform( uniform ) {
  45505. const index = this.uniforms.indexOf( uniform );
  45506. if ( index !== -1 ) {
  45507. this.uniforms.splice( index, 1 );
  45508. }
  45509. return this;
  45510. }
  45511. /**
  45512. * An array with the raw uniform values.
  45513. *
  45514. * @type {Array<number>}
  45515. */
  45516. get values() {
  45517. if ( this._values === null ) {
  45518. this._values = Array.from( this.buffer );
  45519. }
  45520. return this._values;
  45521. }
  45522. /**
  45523. * A Float32 array buffer with the uniform values.
  45524. *
  45525. * @type {Float32Array}
  45526. */
  45527. get buffer() {
  45528. let buffer = this._buffer;
  45529. if ( buffer === null ) {
  45530. const byteLength = this.byteLength;
  45531. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  45532. this._buffer = buffer;
  45533. }
  45534. return buffer;
  45535. }
  45536. /**
  45537. * The byte length of the buffer with correct buffer alignment.
  45538. *
  45539. * @type {number}
  45540. */
  45541. get byteLength() {
  45542. const bytesPerElement = this.bytesPerElement;
  45543. let offset = 0; // global buffer offset in bytes
  45544. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  45545. const uniform = this.uniforms[ i ];
  45546. const boundary = uniform.boundary;
  45547. const itemSize = uniform.itemSize * bytesPerElement; // size of the uniform in bytes
  45548. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  45549. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  45550. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  45551. offset += chunkPadding;
  45552. // Check for chunk overflow
  45553. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  45554. // Add padding to the end of the chunk
  45555. offset += ( GPU_CHUNK_BYTES - chunkStart );
  45556. }
  45557. uniform.offset = offset / bytesPerElement;
  45558. uniform.index = i;
  45559. offset += itemSize;
  45560. }
  45561. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  45562. }
  45563. /**
  45564. * Updates this group by updating each uniform object of
  45565. * the internal uniform list. The uniform objects check if their
  45566. * values has actually changed so this method only returns
  45567. * `true` if there is a real value change.
  45568. *
  45569. * @return {boolean} Whether the uniforms have been updated and
  45570. * must be uploaded to the GPU.
  45571. */
  45572. update() {
  45573. let updated = false;
  45574. for ( const uniform of this.uniforms ) {
  45575. if ( this.updateByType( uniform ) === true ) {
  45576. updated = true;
  45577. }
  45578. }
  45579. return updated;
  45580. }
  45581. /**
  45582. * Releases the buffer.
  45583. */
  45584. release() {
  45585. super.release();
  45586. this._values = null;
  45587. }
  45588. /**
  45589. * Updates a given uniform by calling an update method matching
  45590. * the uniforms type.
  45591. *
  45592. * @param {Uniform} uniform - The uniform to update.
  45593. * @return {boolean} Whether the uniform has been updated or not.
  45594. */
  45595. updateByType( uniform ) {
  45596. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  45597. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  45598. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  45599. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  45600. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  45601. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  45602. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  45603. error( 'WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  45604. }
  45605. /**
  45606. * Updates a given Number uniform.
  45607. *
  45608. * @param {NumberUniform} uniform - The Number uniform.
  45609. * @return {boolean} Whether the uniform has been updated or not.
  45610. */
  45611. updateNumber( uniform ) {
  45612. let updated = false;
  45613. const a = this.values;
  45614. const v = uniform.getValue();
  45615. const offset = uniform.offset;
  45616. const type = uniform.getType();
  45617. if ( a[ offset ] !== v ) {
  45618. const b = this._getBufferForType( type );
  45619. b[ offset ] = a[ offset ] = v;
  45620. updated = true;
  45621. this.addUniformUpdateRange( uniform );
  45622. }
  45623. return updated;
  45624. }
  45625. /**
  45626. * Updates a given Vector2 uniform.
  45627. *
  45628. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  45629. * @return {boolean} Whether the uniform has been updated or not.
  45630. */
  45631. updateVector2( uniform ) {
  45632. let updated = false;
  45633. const a = this.values;
  45634. const v = uniform.getValue();
  45635. const offset = uniform.offset;
  45636. const type = uniform.getType();
  45637. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  45638. const b = this._getBufferForType( type );
  45639. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  45640. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  45641. updated = true;
  45642. this.addUniformUpdateRange( uniform );
  45643. }
  45644. return updated;
  45645. }
  45646. /**
  45647. * Updates a given Vector3 uniform.
  45648. *
  45649. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  45650. * @return {boolean} Whether the uniform has been updated or not.
  45651. */
  45652. updateVector3( uniform ) {
  45653. let updated = false;
  45654. const a = this.values;
  45655. const v = uniform.getValue();
  45656. const offset = uniform.offset;
  45657. const type = uniform.getType();
  45658. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  45659. const b = this._getBufferForType( type );
  45660. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  45661. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  45662. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  45663. updated = true;
  45664. this.addUniformUpdateRange( uniform );
  45665. }
  45666. return updated;
  45667. }
  45668. /**
  45669. * Updates a given Vector4 uniform.
  45670. *
  45671. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  45672. * @return {boolean} Whether the uniform has been updated or not.
  45673. */
  45674. updateVector4( uniform ) {
  45675. let updated = false;
  45676. const a = this.values;
  45677. const v = uniform.getValue();
  45678. const offset = uniform.offset;
  45679. const type = uniform.getType();
  45680. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 3 ] !== v.w ) {
  45681. const b = this._getBufferForType( type );
  45682. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  45683. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  45684. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  45685. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  45686. updated = true;
  45687. this.addUniformUpdateRange( uniform );
  45688. }
  45689. return updated;
  45690. }
  45691. /**
  45692. * Updates a given Color uniform.
  45693. *
  45694. * @param {ColorUniform} uniform - The Color uniform.
  45695. * @return {boolean} Whether the uniform has been updated or not.
  45696. */
  45697. updateColor( uniform ) {
  45698. let updated = false;
  45699. const a = this.values;
  45700. const c = uniform.getValue();
  45701. const offset = uniform.offset;
  45702. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  45703. const b = this.buffer;
  45704. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  45705. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  45706. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  45707. updated = true;
  45708. this.addUniformUpdateRange( uniform );
  45709. }
  45710. return updated;
  45711. }
  45712. /**
  45713. * Updates a given Matrix3 uniform.
  45714. *
  45715. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  45716. * @return {boolean} Whether the uniform has been updated or not.
  45717. */
  45718. updateMatrix3( uniform ) {
  45719. let updated = false;
  45720. const a = this.values;
  45721. const e = uniform.getValue().elements;
  45722. const offset = uniform.offset;
  45723. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  45724. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  45725. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  45726. const b = this.buffer;
  45727. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  45728. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  45729. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  45730. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  45731. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  45732. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  45733. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  45734. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  45735. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  45736. updated = true;
  45737. this.addUniformUpdateRange( uniform );
  45738. }
  45739. return updated;
  45740. }
  45741. /**
  45742. * Updates a given Matrix4 uniform.
  45743. *
  45744. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  45745. * @return {boolean} Whether the uniform has been updated or not.
  45746. */
  45747. updateMatrix4( uniform ) {
  45748. let updated = false;
  45749. const a = this.values;
  45750. const e = uniform.getValue().elements;
  45751. const offset = uniform.offset;
  45752. if ( arraysEqual( a, e, offset ) === false ) {
  45753. const b = this.buffer;
  45754. b.set( e, offset );
  45755. setArray( a, e, offset );
  45756. updated = true;
  45757. this.addUniformUpdateRange( uniform );
  45758. }
  45759. return updated;
  45760. }
  45761. /**
  45762. * Returns a typed array that matches the given data type.
  45763. *
  45764. * @private
  45765. * @param {string} type - The data type.
  45766. * @return {TypedArray} The typed array.
  45767. */
  45768. _getBufferForType( type ) {
  45769. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  45770. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  45771. return this.buffer;
  45772. }
  45773. }
  45774. /**
  45775. * Sets the values of the second array to the first array.
  45776. *
  45777. * @private
  45778. * @param {TypedArray} a - The first array.
  45779. * @param {TypedArray} b - The second array.
  45780. * @param {number} offset - An index offset for the first array.
  45781. */
  45782. function setArray( a, b, offset ) {
  45783. for ( let i = 0, l = b.length; i < l; i ++ ) {
  45784. a[ offset + i ] = b[ i ];
  45785. }
  45786. }
  45787. /**
  45788. * Returns `true` if the given arrays are equal.
  45789. *
  45790. * @private
  45791. * @param {TypedArray} a - The first array.
  45792. * @param {TypedArray} b - The second array.
  45793. * @param {number} offset - An index offset for the first array.
  45794. * @return {boolean} Whether the given arrays are equal or not.
  45795. */
  45796. function arraysEqual( a, b, offset ) {
  45797. for ( let i = 0, l = b.length; i < l; i ++ ) {
  45798. if ( a[ offset + i ] !== b[ i ] ) return false;
  45799. }
  45800. return true;
  45801. }
  45802. let _id$3 = 0;
  45803. /**
  45804. * A special form of uniforms group that represents
  45805. * the individual uniforms as node-based uniforms.
  45806. *
  45807. * @private
  45808. * @augments UniformsGroup
  45809. */
  45810. class NodeUniformsGroup extends UniformsGroup {
  45811. /**
  45812. * Constructs a new node-based uniforms group.
  45813. *
  45814. * @param {string} name - The group's name.
  45815. * @param {UniformGroupNode} groupNode - The uniform group node.
  45816. */
  45817. constructor( name, groupNode ) {
  45818. super( name );
  45819. /**
  45820. * The group's ID.
  45821. *
  45822. * @type {number}
  45823. */
  45824. this.id = _id$3 ++;
  45825. /**
  45826. * The uniform group node.
  45827. *
  45828. * @type {UniformGroupNode}
  45829. */
  45830. this.groupNode = groupNode;
  45831. /**
  45832. * This flag can be used for type testing.
  45833. *
  45834. * @type {boolean}
  45835. * @readonly
  45836. * @default true
  45837. */
  45838. this.isNodeUniformsGroup = true;
  45839. }
  45840. }
  45841. /**
  45842. * Represents a sampler binding type.
  45843. *
  45844. * @private
  45845. * @augments Binding
  45846. */
  45847. class Sampler extends Binding {
  45848. /**
  45849. * Constructs a new sampler.
  45850. *
  45851. * @param {string} name - The samplers's name.
  45852. * @param {?Texture} texture - The texture this binding is referring to.
  45853. */
  45854. constructor( name, texture ) {
  45855. super( name );
  45856. /**
  45857. * The texture the sampler is referring to.
  45858. *
  45859. * @private
  45860. * @type {?Texture}
  45861. */
  45862. this._texture = texture;
  45863. /**
  45864. * The binding's version.
  45865. *
  45866. * @type {number}
  45867. */
  45868. this.version = -1;
  45869. /**
  45870. * The binding's generation which is an additional version
  45871. * qualifier.
  45872. *
  45873. * @type {?number}
  45874. * @default null
  45875. */
  45876. this.generation = null;
  45877. /**
  45878. * The binding's sampler key.
  45879. *
  45880. * @type {string}
  45881. * @default ''
  45882. */
  45883. this.samplerKey = '';
  45884. /**
  45885. * This flag can be used for type testing.
  45886. *
  45887. * @type {boolean}
  45888. * @readonly
  45889. * @default true
  45890. */
  45891. this.isSampler = true;
  45892. }
  45893. /**
  45894. * Sets the texture of this sampler.
  45895. *
  45896. * @param {Texture} value - The texture to set.
  45897. */
  45898. set texture( value ) {
  45899. if ( this._texture === value ) return;
  45900. this._texture = value;
  45901. this.reset();
  45902. }
  45903. /**
  45904. * Gets the texture of this sampler.
  45905. * @return {?Texture} The texture.
  45906. */
  45907. get texture() {
  45908. return this._texture;
  45909. }
  45910. /**
  45911. * Updates the binding.
  45912. *
  45913. * @return {boolean} Whether the texture has been updated and must be
  45914. * uploaded to the GPU.
  45915. */
  45916. update() {
  45917. const { texture, version } = this;
  45918. if ( version !== texture.version ) {
  45919. this.version = texture.version;
  45920. return true;
  45921. }
  45922. return false;
  45923. }
  45924. /**
  45925. * Resets the version and generation. This is used when the texture
  45926. * the binding is pointing to is disposed or exchanged.
  45927. */
  45928. reset() {
  45929. this.generation = null;
  45930. this.version = -1;
  45931. }
  45932. /**
  45933. * Releases the texture reference.
  45934. */
  45935. release() {
  45936. this._texture = null;
  45937. }
  45938. }
  45939. let _id$2 = 0;
  45940. /**
  45941. * Represents a sampled texture binding type.
  45942. *
  45943. * @private
  45944. * @augments Sampler
  45945. */
  45946. class SampledTexture extends Sampler {
  45947. /**
  45948. * Constructs a new sampled texture.
  45949. *
  45950. * @param {string} name - The sampled texture's name.
  45951. * @param {?Texture} texture - The texture this binding is referring to.
  45952. */
  45953. constructor( name, texture ) {
  45954. super( name, texture );
  45955. /**
  45956. * This identifier.
  45957. *
  45958. * @type {number}
  45959. */
  45960. this.id = _id$2 ++;
  45961. /**
  45962. * Whether the texture is a storage texture or not.
  45963. *
  45964. * @type {boolean}
  45965. * @default false
  45966. */
  45967. this.store = false;
  45968. /**
  45969. * The mip level to bind for storage textures.
  45970. *
  45971. * @type {number}
  45972. * @default 0
  45973. */
  45974. this.mipLevel = 0;
  45975. /**
  45976. * This flag can be used for type testing.
  45977. *
  45978. * @type {boolean}
  45979. * @readonly
  45980. * @default true
  45981. */
  45982. this.isSampledTexture = true;
  45983. }
  45984. }
  45985. /**
  45986. * A special form of sampled texture binding type.
  45987. * It's texture value is managed by a node object.
  45988. *
  45989. * @private
  45990. * @augments SampledTexture
  45991. */
  45992. class NodeSampledTexture extends SampledTexture {
  45993. /**
  45994. * Constructs a new node-based sampled texture.
  45995. *
  45996. * @param {string} name - The textures's name.
  45997. * @param {TextureNode} textureNode - The texture node.
  45998. * @param {UniformGroupNode} groupNode - The uniform group node.
  45999. * @param {?string} [access=null] - The access type.
  46000. */
  46001. constructor( name, textureNode, groupNode, access = null ) {
  46002. super( name, textureNode ? textureNode.value : null );
  46003. /**
  46004. * The texture node.
  46005. *
  46006. * @type {TextureNode}
  46007. */
  46008. this.textureNode = textureNode;
  46009. /**
  46010. * The uniform group node.
  46011. *
  46012. * @type {UniformGroupNode}
  46013. */
  46014. this.groupNode = groupNode;
  46015. /**
  46016. * The access type.
  46017. *
  46018. * @type {?string}
  46019. * @default null
  46020. */
  46021. this.access = access;
  46022. }
  46023. /**
  46024. * Updates the binding.
  46025. *
  46026. * @return {boolean} Whether the texture has been updated and must be
  46027. * uploaded to the GPU.
  46028. */
  46029. update() {
  46030. const { textureNode } = this;
  46031. if ( this.texture !== textureNode.value ) {
  46032. this.texture = textureNode.value;
  46033. return true;
  46034. }
  46035. return super.update();
  46036. }
  46037. }
  46038. /**
  46039. * A special form of sampled cube texture binding type.
  46040. * It's texture value is managed by a node object.
  46041. *
  46042. * @private
  46043. * @augments NodeSampledTexture
  46044. */
  46045. class NodeSampledCubeTexture extends NodeSampledTexture {
  46046. /**
  46047. * Constructs a new node-based sampled cube texture.
  46048. *
  46049. * @param {string} name - The textures's name.
  46050. * @param {TextureNode} textureNode - The texture node.
  46051. * @param {UniformGroupNode} groupNode - The uniform group node.
  46052. * @param {?string} [access=null] - The access type.
  46053. */
  46054. constructor( name, textureNode, groupNode, access = null ) {
  46055. super( name, textureNode, groupNode, access );
  46056. /**
  46057. * This flag can be used for type testing.
  46058. *
  46059. * @type {boolean}
  46060. * @readonly
  46061. * @default true
  46062. */
  46063. this.isSampledCubeTexture = true;
  46064. }
  46065. }
  46066. /**
  46067. * A special form of sampled 3D texture binding type.
  46068. * It's texture value is managed by a node object.
  46069. *
  46070. * @private
  46071. * @augments NodeSampledTexture
  46072. */
  46073. class NodeSampledTexture3D extends NodeSampledTexture {
  46074. /**
  46075. * Constructs a new node-based sampled 3D texture.
  46076. *
  46077. * @param {string} name - The textures's name.
  46078. * @param {TextureNode} textureNode - The texture node.
  46079. * @param {UniformGroupNode} groupNode - The uniform group node.
  46080. * @param {?string} [access=null] - The access type.
  46081. */
  46082. constructor( name, textureNode, groupNode, access = null ) {
  46083. super( name, textureNode, groupNode, access );
  46084. /**
  46085. * This flag can be used for type testing.
  46086. *
  46087. * @type {boolean}
  46088. * @readonly
  46089. * @default true
  46090. */
  46091. this.isSampledTexture3D = true;
  46092. }
  46093. }
  46094. const glslPolyfills = {
  46095. bitcast_int_uint: new CodeNode( /* glsl */'uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }' ),
  46096. bitcast_uint_int: new CodeNode( /* glsl */'uint tsl_bitcast_uint_to_int ( uint x ) { return floatBitsToInt( uintBitsToFloat ( x ) ); }' ),
  46097. textureGather: new CodeNode( /* glsl */`
  46098. vec4 tsl_textureGather( const int comp, sampler2D map, vec2 coord, ivec2 offset, bool flipY ) {
  46099. if ( flipY ) offset.y = - offset.y;
  46100. vec2 size = vec2( textureSize( map, 0 ) );
  46101. vec2 st = floor( coord * size + vec2( offset ) - 0.5 );
  46102. vec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;
  46103. vec4 ret = vec4(
  46104. textureLod( map, ij.xw, 0.0 )[ comp ],
  46105. textureLod( map, ij.zw, 0.0 )[ comp ],
  46106. textureLod( map, ij.zy, 0.0 )[ comp ],
  46107. textureLod( map, ij.xy, 0.0 )[ comp ]
  46108. );
  46109. return flipY ? ret.wzyx : ret;
  46110. }
  46111. ` ),
  46112. textureGatherArray: new CodeNode( /* glsl */`
  46113. vec4 tsl_textureGather_array( const int comp, sampler2DArray map, vec3 coord, ivec2 offset, bool flipY ) {
  46114. if ( flipY ) offset.y = - offset.y;
  46115. vec2 size = vec2( textureSize( map, 0 ).xy );
  46116. vec2 st = floor( coord.xy * size + vec2( offset ) - 0.5 );
  46117. vec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;
  46118. vec4 ret = vec4(
  46119. textureLod( map, vec3( ij.xw, coord.z ), 0.0 )[ comp ],
  46120. textureLod( map, vec3( ij.zw, coord.z ), 0.0 )[ comp ],
  46121. textureLod( map, vec3( ij.zy, coord.z ), 0.0 )[ comp ],
  46122. textureLod( map, vec3( ij.xy, coord.z ), 0.0 )[ comp ]
  46123. );
  46124. return flipY ? ret.wzyx : ret;
  46125. }
  46126. ` ),
  46127. textureGatherCompare: new CodeNode( /* glsl */`
  46128. vec4 tsl_textureGatherCompare( sampler2DShadow map, vec2 coord, ivec2 offset, float ref, bool flipY ) {
  46129. if ( flipY ) offset.y = - offset.y;
  46130. vec2 size = vec2( textureSize( map, 0 ) );
  46131. vec2 st = floor( coord * size + vec2( offset ) - 0.5 );
  46132. vec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;
  46133. vec4 ret = vec4(
  46134. textureLod( map, vec3( ij.xw, ref ), 0.0 ),
  46135. textureLod( map, vec3( ij.zw, ref ), 0.0 ),
  46136. textureLod( map, vec3( ij.zy, ref ), 0.0 ),
  46137. textureLod( map, vec3( ij.xy, ref ), 0.0 )
  46138. );
  46139. return flipY ? ret.wzyx : ret;
  46140. }
  46141. ` ),
  46142. textureGatherCompareArray: new CodeNode( /* glsl */`
  46143. vec4 tsl_textureGatherCompare_array( sampler2DArrayShadow map, vec3 coord, ivec2 offset, float ref, bool flipY ) {
  46144. if ( flipY ) offset.y = - offset.y;
  46145. vec2 size = vec2( textureSize( map, 0 ).xy );
  46146. vec2 st = floor( coord.xy * size + vec2( offset ) - 0.5 );
  46147. vec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;
  46148. vec4 ret = vec4(
  46149. texture( map, vec4( ij.xw, coord.z, ref ) ),
  46150. texture( map, vec4( ij.zw, coord.z, ref ) ),
  46151. texture( map, vec4( ij.zy, coord.z, ref ) ),
  46152. texture( map, vec4( ij.xy, coord.z, ref ) )
  46153. );
  46154. return flipY ? ret.wzyx : ret;
  46155. }
  46156. ` )
  46157. };
  46158. const glslMethods = {
  46159. equals: 'equal',
  46160. bitcast_float_int: 'floatBitsToInt',
  46161. bitcast_int_float: 'intBitsToFloat',
  46162. bitcast_uint_float: 'uintBitsToFloat',
  46163. bitcast_float_uint: 'floatBitsToUint',
  46164. bitcast_uint_int: 'tsl_bitcast_uint_to_int',
  46165. bitcast_int_uint: 'tsl_bitcast_int_to_uint',
  46166. floatpack_snorm_2x16: 'packSnorm2x16',
  46167. floatpack_unorm_2x16: 'packUnorm2x16',
  46168. floatpack_float16_2x16: 'packHalf2x16',
  46169. floatunpack_snorm_2x16: 'unpackSnorm2x16',
  46170. floatunpack_unorm_2x16: 'unpackUnorm2x16',
  46171. floatunpack_float16_2x16: 'unpackHalf2x16'
  46172. };
  46173. const precisionLib = {
  46174. low: 'lowp',
  46175. medium: 'mediump',
  46176. high: 'highp'
  46177. };
  46178. const supports$1 = {
  46179. swizzleAssign: true,
  46180. storageBuffer: false
  46181. };
  46182. const interpolationTypeMap = {
  46183. perspective: 'smooth',
  46184. linear: 'noperspective'
  46185. };
  46186. const interpolationModeMap = {
  46187. 'centroid': 'centroid'
  46188. };
  46189. const defaultPrecisions = `
  46190. precision highp float;
  46191. precision highp int;
  46192. precision highp sampler2D;
  46193. precision highp sampler3D;
  46194. precision highp samplerCube;
  46195. precision highp sampler2DArray;
  46196. precision highp usampler2D;
  46197. precision highp usampler3D;
  46198. precision highp usamplerCube;
  46199. precision highp usampler2DArray;
  46200. precision highp isampler2D;
  46201. precision highp isampler3D;
  46202. precision highp isamplerCube;
  46203. precision highp isampler2DArray;
  46204. precision highp sampler2DShadow;
  46205. precision highp sampler2DArrayShadow;
  46206. precision highp samplerCubeShadow;
  46207. `;
  46208. const glslReservedKeywords = new Set( [
  46209. // keywords
  46210. 'const', 'uniform', 'buffer', 'shared', 'attribute', 'varying', 'coherent', 'volatile', 'restrict',
  46211. 'readonly', 'writeonly', 'atomic_uint', 'layout', 'centroid', 'flat', 'smooth', 'noperspective',
  46212. 'patch', 'sample', 'invariant', 'precise', 'break', 'continue', 'do', 'for', 'while', 'switch',
  46213. 'case', 'default', 'if', 'else', 'subroutine', 'in', 'out', 'inout', 'int', 'void', 'bool', 'true',
  46214. 'false', 'float', 'double', 'discard', 'return', 'vec2', 'vec3', 'vec4', 'ivec2', 'ivec3', 'ivec4',
  46215. 'bvec2', 'bvec3', 'bvec4', 'uint', 'uvec2', 'uvec3', 'uvec4', 'dvec2', 'dvec3', 'dvec4', 'mat2',
  46216. 'mat3', 'mat4', 'mat2x2', 'mat2x3', 'mat2x4', 'mat3x2', 'mat3x3', 'mat3x4', 'mat4x2', 'mat4x3',
  46217. 'mat4x4', 'dmat2', 'dmat3', 'dmat4', 'dmat2x2', 'dmat2x3', 'dmat2x4', 'dmat3x2', 'dmat3x3',
  46218. 'dmat3x4', 'dmat4x2', 'dmat4x3', 'dmat4x4', 'lowp', 'mediump', 'highp', 'precision', 'sampler2D',
  46219. 'sampler3D', 'samplerCube', 'sampler2DShadow', 'samplerCubeShadow', 'sampler2DArray',
  46220. 'sampler2DArrayShadow', 'isampler2D', 'isampler3D', 'isamplerCube', 'isampler2DArray', 'usampler2D',
  46221. 'usampler3D', 'usamplerCube', 'usampler2DArray', 'struct',
  46222. // reserved for future use
  46223. 'common', 'partition', 'active', 'asm', 'class', 'union', 'enum', 'typedef', 'template', 'this',
  46224. 'resource', 'goto', 'inline', 'noinline', 'public', 'static', 'extern', 'external', 'interface',
  46225. 'long', 'short', 'half', 'fixed', 'unsigned', 'superp', 'input', 'output', 'hvec2', 'hvec3',
  46226. 'hvec4', 'fvec2', 'fvec3', 'fvec4', 'sampler3DRect', 'filter', 'sizeof', 'cast', 'namespace',
  46227. 'using',
  46228. // generated entry points
  46229. 'main'
  46230. ] );
  46231. /**
  46232. * A node builder targeting GLSL.
  46233. *
  46234. * This module generates GLSL shader code from node materials and also
  46235. * generates the respective bindings and vertex buffer definitions. These
  46236. * data are later used by the renderer to create render and compute pipelines
  46237. * for render objects.
  46238. *
  46239. * @augments NodeBuilder
  46240. */
  46241. class GLSLNodeBuilder extends NodeBuilder {
  46242. /**
  46243. * Constructs a new GLSL node builder renderer.
  46244. *
  46245. * @param {Object3D} object - The 3D object.
  46246. * @param {Renderer} renderer - The renderer.
  46247. */
  46248. constructor( object, renderer ) {
  46249. super( object, renderer, new GLSLNodeParser() );
  46250. /**
  46251. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  46252. * another dictionary which manages UBOs per group ('render','frame','object').
  46253. *
  46254. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  46255. */
  46256. this.uniformGroups = {};
  46257. /**
  46258. * An array that holds objects defining the varying and attribute data in
  46259. * context of Transform Feedback.
  46260. *
  46261. * @type {Array<Object<string,AttributeNode|string>>}
  46262. */
  46263. this.transforms = [];
  46264. /**
  46265. * A dictionary that holds for each shader stage a Map of used extensions.
  46266. *
  46267. * @type {Object<string,Map<string,Object>>}
  46268. */
  46269. this.extensions = {};
  46270. /**
  46271. * A dictionary that holds for each shader stage an Array of used builtins.
  46272. *
  46273. * @type {Object<string,Array<string>>}
  46274. */
  46275. this.builtins = { vertex: [], fragment: [], compute: [] };
  46276. }
  46277. /**
  46278. * Checks if the given texture requires a manual conversion to the working color space.
  46279. *
  46280. * @param {Texture} texture - The texture to check.
  46281. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  46282. */
  46283. needsToWorkingColorSpace( texture ) {
  46284. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  46285. }
  46286. /**
  46287. * Includes the given method name into the current
  46288. * function node.
  46289. *
  46290. * @private
  46291. * @param {string} name - The method name to include.
  46292. * @return {CodeNode} The respective code node.
  46293. */
  46294. _include( name ) {
  46295. const codeNode = glslPolyfills[ name ];
  46296. codeNode.build( this );
  46297. this.addInclude( codeNode );
  46298. return codeNode;
  46299. }
  46300. /**
  46301. * Returns the native shader method name for a given generic name.
  46302. *
  46303. * @param {string} method - The method name to resolve.
  46304. * @return {string} The resolved GLSL method name.
  46305. */
  46306. getMethod( method ) {
  46307. if ( glslPolyfills[ method ] !== undefined ) {
  46308. this._include( method );
  46309. }
  46310. return glslMethods[ method ] || method;
  46311. }
  46312. /**
  46313. * Returns the bitcast method name for a given input and outputType.
  46314. *
  46315. * @param {string} type - The output type to bitcast to.
  46316. * @param {string} inputType - The input type of the.
  46317. * @return {string} The resolved GLSL bitcast invocation.
  46318. */
  46319. getBitcastMethod( type, inputType ) {
  46320. return this.getMethod( `bitcast_${ inputType }_${ type }` );
  46321. }
  46322. /**
  46323. * Returns the float packing method name for a given numeric encoding.
  46324. *
  46325. * @param {string} encoding - The numeric encoding that describes how the float values are mapped to the integer range.
  46326. * @returns {string} The resolved GLSL float packing method name.
  46327. */
  46328. getFloatPackingMethod( encoding ) {
  46329. return this.getMethod( `floatpack_${ encoding }_2x16` );
  46330. }
  46331. /**
  46332. * Returns the float unpacking method name for a given numeric encoding.
  46333. *
  46334. * @param {string} encoding - The numeric encoding that describes how the integer values are mapped to the float range.
  46335. * @returns {string} The resolved GLSL float unpacking method name.
  46336. */
  46337. getFloatUnpackingMethod( encoding ) {
  46338. return this.getMethod( `floatunpack_${ encoding }_2x16` );
  46339. }
  46340. /**
  46341. * Returns the native snippet for a ternary operation.
  46342. *
  46343. * @param {string} condSnippet - The condition determining which expression gets resolved.
  46344. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  46345. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  46346. * @return {string} The resolved method name.
  46347. */
  46348. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  46349. return `${condSnippet} ? ${ifSnippet} : ${elseSnippet}`;
  46350. }
  46351. /**
  46352. * Returns the output struct name. Not relevant for GLSL.
  46353. *
  46354. * @return {string}
  46355. */
  46356. getOutputStructName() {
  46357. return '';
  46358. }
  46359. /**
  46360. * Builds the given shader node.
  46361. *
  46362. * @param {ShaderNodeInternal} shaderNode - The shader node.
  46363. * @return {string} The GLSL function code.
  46364. */
  46365. buildFunctionCode( shaderNode ) {
  46366. const layout = shaderNode.layout;
  46367. const flowData = this.flowShaderNode( shaderNode );
  46368. const parameters = [];
  46369. for ( const input of layout.inputs ) {
  46370. parameters.push( this.getType( input.type ) + ' ' + input.name );
  46371. }
  46372. //
  46373. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  46374. ${ flowData.vars }
  46375. ${ flowData.code }
  46376. return ${ flowData.result };
  46377. }`;
  46378. //
  46379. return code;
  46380. }
  46381. /**
  46382. * Setups the Pixel Buffer Object (PBO) for the given storage
  46383. * buffer node.
  46384. *
  46385. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  46386. */
  46387. setupPBO( storageBufferNode ) {
  46388. const attribute = storageBufferNode.value;
  46389. if ( attribute.pbo === undefined ) {
  46390. const originalArray = attribute.array;
  46391. const numElements = attribute.count * attribute.itemSize;
  46392. const { itemSize } = attribute;
  46393. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  46394. let format = isInteger ? RedIntegerFormat : RedFormat;
  46395. if ( itemSize === 2 ) {
  46396. format = isInteger ? RGIntegerFormat : RGFormat;
  46397. } else if ( itemSize === 3 ) {
  46398. format = isInteger ? RGBIntegerFormat : RGBFormat;
  46399. } else if ( itemSize === 4 ) {
  46400. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  46401. }
  46402. const typeMap = {
  46403. Float32Array: FloatType,
  46404. Uint8Array: UnsignedByteType,
  46405. Uint16Array: UnsignedShortType,
  46406. Uint32Array: UnsignedIntType,
  46407. Int8Array: ByteType,
  46408. Int16Array: ShortType,
  46409. Int32Array: IntType,
  46410. Uint8ClampedArray: UnsignedByteType,
  46411. };
  46412. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  46413. let height = Math.ceil( ( numElements / itemSize ) / width );
  46414. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  46415. const newSize = width * height * itemSize;
  46416. const newArray = new originalArray.constructor( newSize );
  46417. newArray.set( originalArray, 0 );
  46418. attribute.array = newArray;
  46419. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  46420. pboTexture.needsUpdate = true;
  46421. pboTexture.isPBOTexture = true;
  46422. const pbo = new TextureNode( pboTexture, null, null );
  46423. pbo.setPrecision( 'high' );
  46424. attribute.pboNode = pbo;
  46425. attribute.pbo = pbo.value;
  46426. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  46427. }
  46428. }
  46429. /**
  46430. * Returns a GLSL snippet that represents the property name of the given node.
  46431. *
  46432. * @param {Node} node - The node.
  46433. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  46434. * @return {string} The property name.
  46435. */
  46436. getPropertyName( node, shaderStage = this.shaderStage ) {
  46437. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  46438. return node.name;
  46439. }
  46440. return super.getPropertyName( node, shaderStage );
  46441. }
  46442. /**
  46443. * Returns whether the given name is a reserved keyword of GLSL.
  46444. *
  46445. * @param {string} name - The name to test.
  46446. * @return {boolean} Whether the name is a reserved keyword or not.
  46447. */
  46448. isReservedKeyword( name ) {
  46449. return glslReservedKeywords.has( name );
  46450. }
  46451. /**
  46452. * Setups the Pixel Buffer Object (PBO) for the given storage
  46453. * buffer node.
  46454. *
  46455. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  46456. * @return {string} The property name.
  46457. */
  46458. generatePBO( storageArrayElementNode ) {
  46459. const { node, indexNode } = storageArrayElementNode;
  46460. const attribute = node.value;
  46461. if ( this.renderer.backend.has( attribute ) ) {
  46462. const attributeData = this.renderer.backend.get( attribute );
  46463. attributeData.pbo = attribute.pbo;
  46464. }
  46465. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  46466. const textureName = this.getPropertyName( nodeUniform );
  46467. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  46468. const indexSnippet = indexNode.build( this, 'uint' );
  46469. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  46470. let propertyName = elementNodeData.propertyName;
  46471. if ( propertyName === undefined ) {
  46472. // property element
  46473. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  46474. propertyName = this.getPropertyName( nodeVar );
  46475. // property size
  46476. const bufferNodeData = this.getDataFromNode( node );
  46477. let propertySizeName = bufferNodeData.propertySizeName;
  46478. if ( propertySizeName === undefined ) {
  46479. propertySizeName = propertyName + 'Size';
  46480. this.getVarFromNode( node, propertySizeName, 'uint' );
  46481. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  46482. bufferNodeData.propertySizeName = propertySizeName;
  46483. }
  46484. //
  46485. const { itemSize } = attribute;
  46486. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  46487. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  46488. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, '0', null, null );
  46489. //
  46490. let prefix = 'vec4';
  46491. if ( attribute.pbo.type === UnsignedIntType ) {
  46492. prefix = 'uvec4';
  46493. } else if ( attribute.pbo.type === IntType ) {
  46494. prefix = 'ivec4';
  46495. }
  46496. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  46497. elementNodeData.propertyName = propertyName;
  46498. }
  46499. return propertyName;
  46500. }
  46501. /**
  46502. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  46503. *
  46504. * @param {?Texture} texture - The texture.
  46505. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46506. * @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  46507. * @param {?string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  46508. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  46509. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  46510. * @return {string} The GLSL snippet.
  46511. */
  46512. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  46513. if ( levelSnippet === null ) levelSnippet = '0';
  46514. let snippet;
  46515. if ( depthSnippet ) {
  46516. if ( offsetSnippet ) {
  46517. snippet = `texelFetchOffset( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), int( ${ levelSnippet } ), ${ offsetSnippet } )`;
  46518. } else {
  46519. snippet = `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), int( ${ levelSnippet } ) )`;
  46520. }
  46521. } else {
  46522. if ( offsetSnippet ) {
  46523. snippet = `texelFetchOffset( ${ textureProperty }, ${ uvIndexSnippet }, int( ${ levelSnippet } ), ${ offsetSnippet } )`;
  46524. } else {
  46525. snippet = `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, int( ${ levelSnippet } ) )`;
  46526. }
  46527. }
  46528. if ( texture !== null && texture.isDepthTexture ) {
  46529. snippet += '.x';
  46530. }
  46531. return snippet;
  46532. }
  46533. /**
  46534. * Generates the GLSL snippet for sampling/loading the given texture.
  46535. *
  46536. * @param {Texture} texture - The texture.
  46537. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46538. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  46539. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  46540. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  46541. * @return {string} The GLSL snippet.
  46542. */
  46543. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet ) {
  46544. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  46545. if ( texture.isDepthTexture ) {
  46546. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } ).x`;
  46547. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  46548. }
  46549. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } )`;
  46550. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  46551. }
  46552. /**
  46553. * Generates the GLSL snippet that resolves the dimensions of the given texture.
  46554. *
  46555. * @param {Texture} texture - The texture.
  46556. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46557. * @param {string} levelSnippet - A GLSL snippet that represents the mip level.
  46558. * @return {string} The GLSL snippet.
  46559. */
  46560. generateTextureSize( texture, textureProperty, levelSnippet ) {
  46561. return `textureSize( ${ textureProperty }, ${ levelSnippet } )`;
  46562. }
  46563. /**
  46564. * Generates the GLSL snippet when sampling textures with explicit mip level.
  46565. *
  46566. * @param {Texture} texture - The texture.
  46567. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46568. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  46569. * @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  46570. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  46571. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  46572. * @return {string} The GLSL snippet.
  46573. */
  46574. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  46575. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  46576. if ( offsetSnippet ) {
  46577. return `textureLodOffset( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  46578. }
  46579. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  46580. }
  46581. /**
  46582. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  46583. *
  46584. * @param {Texture} texture - The texture.
  46585. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46586. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  46587. * @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  46588. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  46589. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  46590. * @return {string} The GLSL snippet.
  46591. */
  46592. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet ) {
  46593. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  46594. if ( offsetSnippet ) {
  46595. return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet }, ${ biasSnippet } )`;
  46596. }
  46597. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  46598. }
  46599. /**
  46600. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  46601. *
  46602. * @param {Texture} texture - The texture.
  46603. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46604. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  46605. * @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
  46606. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  46607. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  46608. * @return {string} The GLSL snippet.
  46609. */
  46610. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet ) {
  46611. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  46612. if ( offsetSnippet ) {
  46613. return `textureGradOffset( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  46614. }
  46615. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  46616. }
  46617. /**
  46618. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  46619. * against a reference value.
  46620. *
  46621. * @param {Texture} texture - The texture.
  46622. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46623. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  46624. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  46625. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  46626. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  46627. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  46628. * @return {string} The GLSL snippet.
  46629. */
  46630. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  46631. if ( shaderStage === 'fragment' ) {
  46632. // Cube shadow maps use vec4(direction, compareValue)
  46633. if ( texture.isCubeTexture ) {
  46634. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ compareSnippet } ) )`;
  46635. }
  46636. if ( depthSnippet ) {
  46637. if ( offsetSnippet ) {
  46638. return `textureOffset( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  46639. }
  46640. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ) )`;
  46641. }
  46642. if ( offsetSnippet ) {
  46643. return `textureOffset( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  46644. }
  46645. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  46646. } else {
  46647. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  46648. }
  46649. }
  46650. /**
  46651. * Generates the GLSL snippet for gathering four texels from the given texture.
  46652. *
  46653. * @param {Texture} texture - The texture.
  46654. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46655. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  46656. * @param {string} gatherSnippet - A GLSL snippet that represents the index of the channel to read.
  46657. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  46658. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  46659. * @param {?string} flipYSnippet - A GLSL snippet that represents the y-flip. Only used for WebGL.
  46660. * @return {string} The GLSL snippet.
  46661. */
  46662. generateTextureGather( texture, textureProperty, uvSnippet, gatherSnippet, depthSnippet, offsetSnippet, flipYSnippet ) {
  46663. if ( texture.isDepthTexture ) gatherSnippet = '0';
  46664. if ( offsetSnippet === null ) offsetSnippet = 'ivec2( 0 )';
  46665. if ( flipYSnippet === null ) flipYSnippet = 'false';
  46666. if ( depthSnippet ) {
  46667. this._include( 'textureGatherArray' );
  46668. return `tsl_textureGather_array( ${gatherSnippet}, ${ textureProperty }, vec3( ${ uvSnippet }, ${ depthSnippet } ), ${ offsetSnippet }, ${ flipYSnippet } )`;
  46669. }
  46670. this._include( 'textureGather' );
  46671. return `tsl_textureGather( ${gatherSnippet}, ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet }, ${ flipYSnippet } )`;
  46672. }
  46673. /**
  46674. * Generates the GLSL snippet for performing a depth comparison on four texels in the given depth texture.
  46675. *
  46676. * @param {Texture} texture - The texture.
  46677. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46678. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  46679. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  46680. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  46681. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  46682. * @param {?string} flipYSnippet - A GLSL snippet that represents the y-flip. Only used for WebGL.
  46683. * @return {string} The GLSL snippet.
  46684. */
  46685. generateTextureGatherCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, flipYSnippet ) {
  46686. if ( offsetSnippet === null ) offsetSnippet = 'ivec2( 0 )';
  46687. if ( flipYSnippet === null ) flipYSnippet = 'false';
  46688. if ( depthSnippet ) {
  46689. this._include( 'textureGatherCompareArray' );
  46690. return `tsl_textureGatherCompare_array( ${ textureProperty }, vec3( ${ uvSnippet }, ${depthSnippet} ), ${ offsetSnippet }, ${ compareSnippet }, ${ flipYSnippet } )`;
  46691. }
  46692. this._include( 'textureGatherCompare' );
  46693. return `tsl_textureGatherCompare( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet }, ${ compareSnippet }, ${ flipYSnippet } )`;
  46694. }
  46695. /**
  46696. * Returns the uniforms of the given shader stage as a GLSL string.
  46697. *
  46698. * @param {string} shaderStage - The shader stage.
  46699. * @return {string} The GLSL snippet that defines the uniforms.
  46700. */
  46701. getUniforms( shaderStage ) {
  46702. const uniforms = this.uniforms[ shaderStage ];
  46703. const bindingSnippets = [];
  46704. const uniformGroups = {};
  46705. for ( const uniform of uniforms ) {
  46706. let snippet = null;
  46707. let group = false;
  46708. if ( uniform.type === 'texture' || uniform.type === 'texture3D' ) {
  46709. const textureNode = uniform.node;
  46710. const texture = textureNode.value;
  46711. let typePrefix = '';
  46712. if ( texture.isDataTexture === true || texture.isData3DTexture === true ) {
  46713. if ( texture.type === UnsignedIntType ) {
  46714. typePrefix = 'u';
  46715. } else if ( texture.type === IntType ) {
  46716. typePrefix = 'i';
  46717. }
  46718. }
  46719. if ( uniform.type === 'texture3D' && texture.isArrayTexture === false ) {
  46720. snippet = `${typePrefix}sampler3D ${ uniform.name };`;
  46721. } else if ( texture.compareFunction && textureNode.compareNode !== null ) {
  46722. if ( texture.isArrayTexture === true ) {
  46723. snippet = `sampler2DArrayShadow ${ uniform.name };`;
  46724. } else {
  46725. snippet = `sampler2DShadow ${ uniform.name };`;
  46726. }
  46727. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  46728. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  46729. } else {
  46730. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  46731. }
  46732. } else if ( uniform.type === 'cubeTexture' ) {
  46733. snippet = `samplerCube ${ uniform.name };`;
  46734. } else if ( uniform.type === 'cubeDepthTexture' ) {
  46735. const texture = uniform.node.value;
  46736. if ( texture.compareFunction ) {
  46737. snippet = `samplerCubeShadow ${ uniform.name };`;
  46738. } else {
  46739. snippet = `samplerCube ${ uniform.name };`;
  46740. }
  46741. } else if ( uniform.type === 'buffer' ) {
  46742. const bufferNode = uniform.node;
  46743. const bufferType = this.getType( bufferNode.bufferType );
  46744. const bufferCount = bufferNode.bufferCount;
  46745. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  46746. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  46747. } else {
  46748. const groupName = uniform.groupNode.name;
  46749. // Check if this group has already been processed
  46750. if ( uniformGroups[ groupName ] === undefined ) {
  46751. // Get the shared uniform group that contains uniforms from all stages
  46752. const sharedUniformGroup = this.uniformGroups[ groupName ];
  46753. if ( sharedUniformGroup !== undefined ) {
  46754. // Generate snippets for ALL uniforms in this shared group
  46755. const snippets = [];
  46756. for ( const sharedUniform of sharedUniformGroup.uniforms ) {
  46757. const type = sharedUniform.getType();
  46758. const vectorType = this.getVectorType( type );
  46759. const precision = sharedUniform.nodeUniform.node.precision;
  46760. let uniformSnippet = `${ vectorType } ${ sharedUniform.name };`;
  46761. if ( precision !== null ) {
  46762. uniformSnippet = precisionLib[ precision ] + ' ' + uniformSnippet;
  46763. }
  46764. snippets.push( '\t' + uniformSnippet );
  46765. }
  46766. uniformGroups[ groupName ] = snippets;
  46767. }
  46768. }
  46769. group = true;
  46770. }
  46771. if ( ! group ) {
  46772. const precision = uniform.node.precision;
  46773. if ( precision !== null ) {
  46774. snippet = precisionLib[ precision ] + ' ' + snippet;
  46775. }
  46776. snippet = 'uniform ' + snippet;
  46777. bindingSnippets.push( snippet );
  46778. }
  46779. }
  46780. let output = '';
  46781. for ( const name in uniformGroups ) {
  46782. const groupSnippets = uniformGroups[ name ];
  46783. output += this._getGLSLUniformStruct( name, groupSnippets.join( '\n' ) ) + '\n';
  46784. }
  46785. output += bindingSnippets.join( '\n' );
  46786. return output;
  46787. }
  46788. /**
  46789. * Returns the type for a given buffer attribute.
  46790. *
  46791. * @param {BufferAttribute} attribute - The buffer attribute.
  46792. * @return {string} The type.
  46793. */
  46794. getTypeFromAttribute( attribute ) {
  46795. let nodeType = super.getTypeFromAttribute( attribute );
  46796. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  46797. let dataAttribute = attribute;
  46798. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  46799. const array = dataAttribute.array;
  46800. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  46801. nodeType = nodeType.slice( 1 );
  46802. }
  46803. }
  46804. return nodeType;
  46805. }
  46806. /**
  46807. * Returns the shader attributes of the given shader stage as a GLSL string.
  46808. *
  46809. * @param {string} shaderStage - The shader stage.
  46810. * @return {string} The GLSL snippet that defines the shader attributes.
  46811. */
  46812. getAttributes( shaderStage ) {
  46813. let snippet = '';
  46814. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  46815. const attributes = this.getAttributesArray();
  46816. let location = 0;
  46817. for ( const attribute of attributes ) {
  46818. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  46819. }
  46820. }
  46821. return snippet;
  46822. }
  46823. /**
  46824. * Returns the members of the given struct type node as a GLSL string.
  46825. *
  46826. * @param {StructTypeNode} struct - The struct type node.
  46827. * @return {string} The GLSL snippet that defines the struct members.
  46828. */
  46829. getStructMembers( struct ) {
  46830. const snippets = [];
  46831. for ( const member of struct.members ) {
  46832. snippets.push( `\t${ member.type } ${ member.name };` );
  46833. }
  46834. return snippets.join( '\n' );
  46835. }
  46836. /**
  46837. * Returns the structs of the given shader stage as a GLSL string.
  46838. *
  46839. * @param {string} shaderStage - The shader stage.
  46840. * @return {string} The GLSL snippet that defines the structs.
  46841. */
  46842. getStructs( shaderStage ) {
  46843. const snippets = [];
  46844. const structs = this.structs[ shaderStage ];
  46845. const outputSnippet = [];
  46846. for ( const struct of structs ) {
  46847. if ( struct.output ) {
  46848. for ( const member of struct.members ) {
  46849. outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
  46850. }
  46851. } else {
  46852. let snippet = 'struct ' + struct.name + ' {\n';
  46853. snippet += this.getStructMembers( struct );
  46854. snippet += '\n};\n';
  46855. snippets.push( snippet );
  46856. }
  46857. }
  46858. if ( shaderStage === 'fragment' && outputSnippet.length === 0 ) {
  46859. outputSnippet.push( `layout( location = 0 ) out ${ this.getOutputType() } fragColor;` );
  46860. }
  46861. return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
  46862. }
  46863. /**
  46864. * Returns the varyings of the given shader stage as a GLSL string.
  46865. *
  46866. * @param {string} shaderStage - The shader stage.
  46867. * @return {string} The GLSL snippet that defines the varyings.
  46868. */
  46869. getVaryings( shaderStage ) {
  46870. let snippet = '';
  46871. const varyings = this.varyings;
  46872. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  46873. for ( const varying of varyings ) {
  46874. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  46875. const type = this.getType( varying.type );
  46876. if ( varying.needsInterpolation ) {
  46877. if ( varying.interpolationType ) {
  46878. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  46879. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  46880. snippet += `${ interpolationType } ${ sampling } out ${ type } ${ varying.name };\n`;
  46881. } else {
  46882. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  46883. snippet += `${ flat }out ${ type } ${ varying.name };\n`;
  46884. }
  46885. } else {
  46886. snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
  46887. }
  46888. }
  46889. } else if ( shaderStage === 'fragment' ) {
  46890. for ( const varying of varyings ) {
  46891. if ( varying.needsInterpolation ) {
  46892. const type = this.getType( varying.type );
  46893. if ( varying.interpolationType ) {
  46894. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  46895. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  46896. snippet += `${ interpolationType } ${ sampling } in ${ type } ${ varying.name };\n`;
  46897. } else {
  46898. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  46899. snippet += `${ flat }in ${ type } ${ varying.name };\n`;
  46900. }
  46901. }
  46902. }
  46903. }
  46904. for ( const builtin of this.builtins[ shaderStage ] ) {
  46905. snippet += `${builtin};\n`;
  46906. }
  46907. return snippet;
  46908. }
  46909. /**
  46910. * Returns the vertex index builtin.
  46911. *
  46912. * @return {string} The vertex index.
  46913. */
  46914. getVertexIndex() {
  46915. return 'uint( gl_VertexID )';
  46916. }
  46917. /**
  46918. * Contextually returns either the vertex stage instance index builtin
  46919. * or the linearized index of an compute invocation within a grid of workgroups.
  46920. *
  46921. * @return {string} The instance index.
  46922. */
  46923. getInstanceIndex() {
  46924. return 'uint( gl_InstanceID )';
  46925. }
  46926. /**
  46927. * Returns a builtin representing the index of an invocation within its workgroup.
  46928. *
  46929. * @return {string} The invocation local index.
  46930. */
  46931. getInvocationLocalIndex() {
  46932. const workgroupSize = this.object.workgroupSize;
  46933. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  46934. return `uint( gl_InstanceID ) % ${size}u`;
  46935. }
  46936. /**
  46937. * Returns a builtin representing the size of a subgroup within the current shader.
  46938. */
  46939. getSubgroupSize() {
  46940. error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node' );
  46941. }
  46942. /**
  46943. * Returns a builtin representing the index of an invocation within its subgroup.
  46944. */
  46945. getInvocationSubgroupIndex() {
  46946. error( 'GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node' );
  46947. }
  46948. /**
  46949. * Returns a builtin representing the index of the current invocation's subgroup within its workgroup.
  46950. */
  46951. getSubgroupIndex() {
  46952. error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node' );
  46953. }
  46954. /**
  46955. * Returns the draw index builtin.
  46956. *
  46957. * @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  46958. */
  46959. getDrawIndex() {
  46960. const extensions = this.renderer.backend.extensions;
  46961. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  46962. return 'uint( gl_DrawID )';
  46963. } else {
  46964. return 'nodeUniformDrawId'; // fallback to uniform
  46965. }
  46966. }
  46967. /**
  46968. * Returns the front facing builtin.
  46969. *
  46970. * @return {string} The front facing builtin.
  46971. */
  46972. getFrontFacing() {
  46973. return 'gl_FrontFacing';
  46974. }
  46975. /**
  46976. * Returns the frag coord builtin.
  46977. *
  46978. * @return {string} The frag coord builtin.
  46979. */
  46980. getFragCoord() {
  46981. return 'gl_FragCoord.xy';
  46982. }
  46983. /**
  46984. * Returns the frag depth builtin.
  46985. *
  46986. * @return {string} The frag depth builtin.
  46987. */
  46988. getFragDepth() {
  46989. return 'gl_FragDepth';
  46990. }
  46991. /**
  46992. * Enables the given extension.
  46993. *
  46994. * @param {string} name - The extension name.
  46995. * @param {string} behavior - The extension behavior.
  46996. * @param {string} [shaderStage=this.shaderStage] - The shader stage.
  46997. */
  46998. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  46999. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  47000. if ( map.has( name ) === false ) {
  47001. map.set( name, {
  47002. name,
  47003. behavior
  47004. } );
  47005. }
  47006. }
  47007. /**
  47008. * Returns the enabled extensions of the given shader stage as a GLSL string.
  47009. *
  47010. * @param {string} shaderStage - The shader stage.
  47011. * @return {string} The GLSL snippet that defines the enabled extensions.
  47012. */
  47013. getExtensions( shaderStage ) {
  47014. const snippets = [];
  47015. if ( shaderStage === 'vertex' ) {
  47016. const ext = this.renderer.backend.extensions;
  47017. const isBatchedMesh = this.object.isBatchedMesh;
  47018. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  47019. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  47020. }
  47021. }
  47022. const extensions = this.extensions[ shaderStage ];
  47023. if ( extensions !== undefined ) {
  47024. for ( const { name, behavior } of extensions.values() ) {
  47025. snippets.push( `#extension ${name} : ${behavior}` );
  47026. }
  47027. }
  47028. return snippets.join( '\n' );
  47029. }
  47030. /**
  47031. * Returns the clip distances builtin.
  47032. *
  47033. * @return {string} The clip distances builtin.
  47034. */
  47035. getClipDistance() {
  47036. return 'gl_ClipDistance';
  47037. }
  47038. /**
  47039. * Whether the requested feature is available or not.
  47040. *
  47041. * @param {string} name - The requested feature.
  47042. * @return {boolean} Whether the requested feature is supported or not.
  47043. */
  47044. isAvailable( name ) {
  47045. let result = supports$1[ name ];
  47046. if ( result === undefined ) {
  47047. let extensionName;
  47048. result = false;
  47049. switch ( name ) {
  47050. case 'float32Filterable':
  47051. extensionName = 'OES_texture_float_linear';
  47052. break;
  47053. case 'clipDistance':
  47054. extensionName = 'WEBGL_clip_cull_distance';
  47055. break;
  47056. }
  47057. if ( extensionName !== undefined ) {
  47058. const extensions = this.renderer.backend.extensions;
  47059. if ( extensions.has( extensionName ) ) {
  47060. extensions.get( extensionName );
  47061. result = true;
  47062. }
  47063. }
  47064. supports$1[ name ] = result;
  47065. }
  47066. return result;
  47067. }
  47068. /**
  47069. * Whether to flip texture data along its vertical axis or not.
  47070. *
  47071. * @return {boolean} Returns always `true` in context of GLSL.
  47072. */
  47073. isFlipY() {
  47074. return true;
  47075. }
  47076. /**
  47077. * Enables hardware clipping.
  47078. *
  47079. * @param {string} planeCount - The clipping plane count.
  47080. */
  47081. enableHardwareClipping( planeCount ) {
  47082. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  47083. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  47084. }
  47085. /**
  47086. * Enables multiview.
  47087. */
  47088. enableMultiview() {
  47089. this.enableExtension( 'GL_OVR_multiview2', 'require', 'fragment' );
  47090. this.enableExtension( 'GL_OVR_multiview2', 'require', 'vertex' );
  47091. this.builtins[ 'vertex' ].push( 'layout(num_views = 2) in' );
  47092. }
  47093. /**
  47094. * Registers a transform in context of Transform Feedback.
  47095. *
  47096. * @param {string} varyingName - The varying name.
  47097. * @param {AttributeNode} attributeNode - The attribute node.
  47098. */
  47099. registerTransform( varyingName, attributeNode ) {
  47100. this.transforms.push( { varyingName, attributeNode } );
  47101. }
  47102. /**
  47103. * Returns the transforms of the given shader stage as a GLSL string.
  47104. *
  47105. * @param {string} shaderStage - The shader stage.
  47106. * @return {string} The GLSL snippet that defines the transforms.
  47107. */
  47108. getTransforms( /* shaderStage */ ) {
  47109. const transforms = this.transforms;
  47110. let snippet = '';
  47111. for ( let i = 0; i < transforms.length; i ++ ) {
  47112. const transform = transforms[ i ];
  47113. const attributeName = this.getPropertyName( transform.attributeNode );
  47114. if ( attributeName ) snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  47115. }
  47116. return snippet;
  47117. }
  47118. /**
  47119. * Returns a GLSL struct based on the given name and variables.
  47120. *
  47121. * @private
  47122. * @param {string} name - The struct name.
  47123. * @param {string} vars - The struct variables.
  47124. * @return {string} The GLSL snippet representing a struct.
  47125. */
  47126. _getGLSLUniformStruct( name, vars ) {
  47127. return `
  47128. layout( std140 ) uniform ${name} {
  47129. ${vars}
  47130. };`;
  47131. }
  47132. /**
  47133. * Returns a GLSL vertex shader based on the given shader data.
  47134. *
  47135. * @private
  47136. * @param {Object} shaderData - The shader data.
  47137. * @return {string} The vertex shader.
  47138. */
  47139. _getGLSLVertexCode( shaderData ) {
  47140. return `#version 300 es
  47141. ${ this.getSignature() }
  47142. // extensions
  47143. ${shaderData.extensions}
  47144. // precision
  47145. ${ defaultPrecisions }
  47146. // structs
  47147. ${shaderData.structs}
  47148. // uniforms
  47149. ${shaderData.uniforms}
  47150. // varyings
  47151. ${shaderData.varyings}
  47152. // attributes
  47153. ${shaderData.attributes}
  47154. // vars
  47155. ${shaderData.vars}
  47156. // codes
  47157. ${shaderData.codes}
  47158. void main() {
  47159. // transforms
  47160. ${shaderData.transforms}
  47161. // flow
  47162. ${shaderData.flow}
  47163. gl_PointSize = 1.0;
  47164. }
  47165. `;
  47166. }
  47167. /**
  47168. * Returns a GLSL fragment shader based on the given shader data.
  47169. *
  47170. * @private
  47171. * @param {Object} shaderData - The shader data.
  47172. * @return {string} The vertex shader.
  47173. */
  47174. _getGLSLFragmentCode( shaderData ) {
  47175. return `#version 300 es
  47176. ${ this.getSignature() }
  47177. // extensions
  47178. ${shaderData.extensions}
  47179. // precision
  47180. ${ defaultPrecisions }
  47181. // structs
  47182. ${shaderData.structs}
  47183. // uniforms
  47184. ${shaderData.uniforms}
  47185. // varyings
  47186. ${shaderData.varyings}
  47187. // vars
  47188. ${shaderData.vars}
  47189. // codes
  47190. ${shaderData.codes}
  47191. void main() {
  47192. // flow
  47193. ${shaderData.flow}
  47194. }
  47195. `;
  47196. }
  47197. /**
  47198. * Controls the code build of the shader stages.
  47199. */
  47200. buildCode() {
  47201. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  47202. this.sortBindingGroups();
  47203. for ( const shaderStage in shadersData ) {
  47204. let flow = '// code\n\n';
  47205. flow += this.flowCode[ shaderStage ];
  47206. const flowNodes = this.flowNodes[ shaderStage ];
  47207. const mainNode = flowNodes[ flowNodes.length - 1 ];
  47208. for ( const node of flowNodes ) {
  47209. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  47210. const slotName = node.name;
  47211. if ( slotName ) {
  47212. if ( flow.length > 0 ) flow += '\n';
  47213. flow += `\t// flow -> ${ slotName }\n\t`;
  47214. }
  47215. flow += `${ flowSlotData.code }\n\t`;
  47216. if ( node === mainNode && shaderStage !== 'compute' ) {
  47217. flow += '// result\n\t';
  47218. if ( shaderStage === 'vertex' ) {
  47219. flow += 'gl_Position = ';
  47220. flow += `${ this.format( flowSlotData.result, mainNode.getNodeType( this ), 'vec4' ) };`;
  47221. } else if ( shaderStage === 'fragment' ) {
  47222. if ( ! node.outputNode.isOutputStructNode ) {
  47223. flow += 'fragColor = ';
  47224. flow += `${ this.format( flowSlotData.result, mainNode.getNodeType( this ), this.getOutputType() ) };`;
  47225. }
  47226. }
  47227. }
  47228. }
  47229. const stageData = shadersData[ shaderStage ];
  47230. stageData.extensions = this.getExtensions( shaderStage );
  47231. stageData.uniforms = this.getUniforms( shaderStage );
  47232. stageData.attributes = this.getAttributes( shaderStage );
  47233. stageData.varyings = this.getVaryings( shaderStage );
  47234. stageData.vars = this.getVars( shaderStage, true );
  47235. stageData.structs = this.getStructs( shaderStage );
  47236. stageData.codes = this.getCodes( shaderStage );
  47237. stageData.transforms = this.getTransforms( shaderStage );
  47238. stageData.flow = flow;
  47239. // fallbacks
  47240. if ( shaderStage === 'vertex' ) {
  47241. const ext = this.renderer.backend.extensions;
  47242. if ( this.object.isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) === false ) {
  47243. stageData.uniforms += '\nuniform uint nodeUniformDrawId;\n';
  47244. }
  47245. }
  47246. }
  47247. if ( this.material !== null ) {
  47248. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  47249. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  47250. } else {
  47251. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  47252. }
  47253. }
  47254. /**
  47255. * This method is one of the more important ones since it's responsible
  47256. * for generating a matching binding instance for the given uniform node.
  47257. *
  47258. * These bindings are later used in the renderer to create bind groups
  47259. * and layouts.
  47260. *
  47261. * @param {UniformNode} node - The uniform node.
  47262. * @param {string} type - The node data type.
  47263. * @param {string} shaderStage - The shader stage.
  47264. * @param {?string} [name=null] - An optional uniform name.
  47265. * @return {NodeUniform} The node uniform object.
  47266. */
  47267. getUniformFromNode( node, type, shaderStage, name = null ) {
  47268. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  47269. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  47270. let uniformGPU = nodeData.uniformGPU;
  47271. if ( uniformGPU === undefined ) {
  47272. const group = node.groupNode;
  47273. const groupName = group.name;
  47274. const bindings = this.getBindGroupArray( groupName, shaderStage );
  47275. if ( type === 'texture' ) {
  47276. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  47277. bindings.push( uniformGPU );
  47278. } else if ( type === 'cubeTexture' || type === 'cubeDepthTexture' ) {
  47279. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  47280. bindings.push( uniformGPU );
  47281. } else if ( type === 'texture3D' ) {
  47282. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  47283. bindings.push( uniformGPU );
  47284. } else if ( type === 'buffer' ) {
  47285. uniformNode.name = `buffer${ node.id }`;
  47286. const sharedData = this.getSharedDataFromNode( node );
  47287. let buffer = sharedData.buffer;
  47288. if ( buffer === undefined ) {
  47289. node.name = `NodeBuffer_${ node.id }`;
  47290. buffer = new NodeUniformBuffer( node, group );
  47291. buffer.name = node.name;
  47292. sharedData.buffer = buffer;
  47293. }
  47294. bindings.push( buffer );
  47295. uniformGPU = buffer;
  47296. } else {
  47297. let uniformsGroup = this.uniformGroups[ groupName ];
  47298. if ( uniformsGroup === undefined ) {
  47299. uniformsGroup = new NodeUniformsGroup( groupName, group );
  47300. this.uniformGroups[ groupName ] = uniformsGroup;
  47301. bindings.push( uniformsGroup );
  47302. } else {
  47303. // Add to bindings for this stage if not already present
  47304. if ( bindings.indexOf( uniformsGroup ) === -1 ) {
  47305. bindings.push( uniformsGroup );
  47306. }
  47307. }
  47308. uniformGPU = this.getNodeUniform( uniformNode, type );
  47309. // Only add uniform if not already present in the group (check by name to avoid duplicates across stages)
  47310. const uniformName = uniformGPU.name;
  47311. const alreadyExists = uniformsGroup.uniforms.some( u => u.name === uniformName );
  47312. if ( ! alreadyExists ) {
  47313. uniformsGroup.addUniform( uniformGPU );
  47314. }
  47315. }
  47316. nodeData.uniformGPU = uniformGPU;
  47317. }
  47318. return uniformNode;
  47319. }
  47320. }
  47321. let _vector2 = null;
  47322. let _color4 = null;
  47323. /**
  47324. * Most of the rendering related logic is implemented in the
  47325. * {@link Renderer} module and related management components.
  47326. * Sometimes it is required though to execute commands which are
  47327. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  47328. * This abstract base class defines an interface that encapsulates
  47329. * all backend-related logic. Derived classes for each backend must
  47330. * implement the interface.
  47331. *
  47332. * @abstract
  47333. */
  47334. class Backend {
  47335. /**
  47336. * Constructs a new backend.
  47337. *
  47338. * @param {Object} parameters - An object holding parameters for the backend.
  47339. */
  47340. constructor( parameters = {} ) {
  47341. /**
  47342. * The parameters of the backend.
  47343. *
  47344. * @type {Object}
  47345. */
  47346. this.parameters = Object.assign( {}, parameters );
  47347. /**
  47348. * This weak map holds backend-specific data of objects
  47349. * like textures, attributes or render targets.
  47350. *
  47351. * @type {WeakMap<Object, Object>}
  47352. */
  47353. this.data = new WeakMap();
  47354. /**
  47355. * A reference to the renderer.
  47356. *
  47357. * @type {?Renderer}
  47358. * @default null
  47359. */
  47360. this.renderer = null;
  47361. /**
  47362. * A reference to the canvas element the renderer is drawing to.
  47363. *
  47364. * @type {?(HTMLCanvasElement|OffscreenCanvas)}
  47365. * @default null
  47366. */
  47367. this.domElement = null;
  47368. /**
  47369. * A reference to the timestamp query pool.
  47370. *
  47371. * @type {{render: ?TimestampQueryPool, compute: ?TimestampQueryPool}}
  47372. */
  47373. this.timestampQueryPool = {
  47374. [ TimestampQuery.RENDER ]: null,
  47375. [ TimestampQuery.COMPUTE ]: null
  47376. };
  47377. /**
  47378. * Whether to track timestamps with a Timestamp Query API or not.
  47379. *
  47380. * @type {boolean}
  47381. * @default false
  47382. */
  47383. this.trackTimestamp = ( parameters.trackTimestamp === true );
  47384. }
  47385. /**
  47386. * Initializes the backend so it is ready for usage. Concrete backends
  47387. * are supposed to implement their rendering context creation and related
  47388. * operations in this method.
  47389. *
  47390. * @async
  47391. * @param {Renderer} renderer - The renderer.
  47392. * @return {Promise} A Promise that resolves when the backend has been initialized.
  47393. */
  47394. async init( renderer ) {
  47395. this.renderer = renderer;
  47396. }
  47397. /**
  47398. * The coordinate system of the backend.
  47399. *
  47400. * @abstract
  47401. * @type {number}
  47402. * @readonly
  47403. */
  47404. get coordinateSystem() {}
  47405. // render context
  47406. /**
  47407. * This method is executed at the beginning of a render call and
  47408. * can be used by the backend to prepare the state for upcoming
  47409. * draw calls.
  47410. *
  47411. * @abstract
  47412. * @param {RenderContext} renderContext - The render context.
  47413. */
  47414. beginRender( /*renderContext*/ ) {}
  47415. /**
  47416. * This method is executed at the end of a render call and
  47417. * can be used by the backend to finalize work after draw
  47418. * calls.
  47419. *
  47420. * @abstract
  47421. * @param {RenderContext} renderContext - The render context.
  47422. */
  47423. finishRender( /*renderContext*/ ) {}
  47424. /**
  47425. * Sets the XR rendering destination.
  47426. *
  47427. * Backends that render directly into XR framebuffers can override this hook.
  47428. *
  47429. * @param {?Object} xrTarget - The XR rendering destination.
  47430. */
  47431. setXRTarget( /*xrTarget*/ ) {}
  47432. /**
  47433. * This method is executed at the beginning of a compute call and
  47434. * can be used by the backend to prepare the state for upcoming
  47435. * compute tasks.
  47436. *
  47437. * @abstract
  47438. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  47439. */
  47440. beginCompute( /*computeGroup*/ ) {}
  47441. /**
  47442. * This method is executed at the end of a compute call and
  47443. * can be used by the backend to finalize work after compute
  47444. * tasks.
  47445. *
  47446. * @abstract
  47447. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  47448. */
  47449. finishCompute( /*computeGroup*/ ) {}
  47450. // render object
  47451. /**
  47452. * Executes a draw command for the given render object.
  47453. *
  47454. * @abstract
  47455. * @param {RenderObject} renderObject - The render object to draw.
  47456. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  47457. */
  47458. draw( /*renderObject, info*/ ) { }
  47459. // compute node
  47460. /**
  47461. * Executes a compute command for the given compute node.
  47462. *
  47463. * @abstract
  47464. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  47465. * @param {Node} computeNode - The compute node.
  47466. * @param {Array<BindGroup>} bindings - The bindings.
  47467. * @param {ComputePipeline} computePipeline - The compute pipeline.
  47468. */
  47469. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  47470. // program
  47471. /**
  47472. * Creates a shader program from the given programmable stage.
  47473. *
  47474. * @abstract
  47475. * @param {ProgrammableStage} program - The programmable stage.
  47476. */
  47477. createProgram( /*program*/ ) { }
  47478. /**
  47479. * Destroys the shader program of the given programmable stage.
  47480. *
  47481. * @abstract
  47482. * @param {ProgrammableStage} program - The programmable stage.
  47483. */
  47484. destroyProgram( /*program*/ ) { }
  47485. // bindings
  47486. /**
  47487. * Creates bindings from the given bind group definition.
  47488. *
  47489. * @abstract
  47490. * @param {BindGroup} bindGroup - The bind group.
  47491. * @param {Array<BindGroup>} bindings - Array of bind groups.
  47492. * @param {number} cacheIndex - The cache index.
  47493. * @param {number} version - The version.
  47494. */
  47495. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  47496. /**
  47497. * Updates the given bind group definition.
  47498. *
  47499. * @abstract
  47500. * @param {BindGroup} bindGroup - The bind group.
  47501. * @param {Array<BindGroup>} bindings - Array of bind groups.
  47502. * @param {number} cacheIndex - The cache index.
  47503. * @param {number} version - The version.
  47504. */
  47505. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  47506. /**
  47507. * Updates a buffer binding.
  47508. *
  47509. * @abstract
  47510. * @param {Buffer} binding - The buffer binding to update.
  47511. */
  47512. updateBinding( /*binding*/ ) { }
  47513. // pipeline
  47514. /**
  47515. * Creates a render pipeline for the given render object.
  47516. *
  47517. * @abstract
  47518. * @param {RenderObject} renderObject - The render object.
  47519. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  47520. */
  47521. createRenderPipeline( /*renderObject, promises*/ ) { }
  47522. /**
  47523. * Creates a compute pipeline for the given compute node.
  47524. *
  47525. * @abstract
  47526. * @param {ComputePipeline} computePipeline - The compute pipeline.
  47527. * @param {Array<BindGroup>} bindings - The bindings.
  47528. */
  47529. createComputePipeline( /*computePipeline, bindings*/ ) { }
  47530. // cache key
  47531. /**
  47532. * Returns `true` if the render pipeline requires an update.
  47533. *
  47534. * @abstract
  47535. * @param {RenderObject} renderObject - The render object.
  47536. * @return {boolean} Whether the render pipeline requires an update or not.
  47537. */
  47538. needsRenderUpdate( /*renderObject*/ ) { }
  47539. /**
  47540. * Returns a cache key that is used to identify render pipelines.
  47541. *
  47542. * @abstract
  47543. * @param {RenderObject} renderObject - The render object.
  47544. * @return {string} The cache key.
  47545. */
  47546. getRenderCacheKey( /*renderObject*/ ) { }
  47547. // node builder
  47548. /**
  47549. * Returns a node builder for the given render object.
  47550. *
  47551. * @abstract
  47552. * @param {RenderObject} renderObject - The render object.
  47553. * @param {Renderer} renderer - The renderer.
  47554. * @return {NodeBuilder} The node builder.
  47555. */
  47556. createNodeBuilder( /*renderObject, renderer*/ ) { }
  47557. // textures
  47558. /**
  47559. * Updates a GPU sampler for the given texture.
  47560. *
  47561. * @abstract
  47562. * @param {Sampler} binding - The sampler binding to update.
  47563. * @return {string} The current sampler key.
  47564. */
  47565. updateSampler( /*binding*/ ) { }
  47566. /**
  47567. * Frees the GPU sampler for the given sampler binding.
  47568. *
  47569. * @abstract
  47570. * @param {Sampler} binding - The sampler binding to free.
  47571. */
  47572. destroySampler( /*binding*/ ) { }
  47573. /**
  47574. * Creates a default texture for the given texture that can be used
  47575. * as a placeholder until the actual texture is ready for usage.
  47576. *
  47577. * @abstract
  47578. * @param {Texture} texture - The texture to create a default texture for.
  47579. */
  47580. createDefaultTexture( /*texture*/ ) { }
  47581. /**
  47582. * Defines a texture on the GPU for the given texture object.
  47583. *
  47584. * @abstract
  47585. * @param {Texture} texture - The texture.
  47586. * @param {Object} [options={}] - Optional configuration parameter.
  47587. */
  47588. createTexture( /*texture, options={}*/ ) { }
  47589. /**
  47590. * Uploads the updated texture data to the GPU.
  47591. *
  47592. * @abstract
  47593. * @param {Texture} texture - The texture.
  47594. * @param {Object} [options={}] - Optional configuration parameter.
  47595. */
  47596. updateTexture( /*texture, options = {}*/ ) { }
  47597. /**
  47598. * Generates mipmaps for the given texture.
  47599. *
  47600. * @abstract
  47601. * @param {Texture} texture - The texture.
  47602. */
  47603. generateMipmaps( /*texture*/ ) { }
  47604. /**
  47605. * Destroys the GPU data for the given texture object.
  47606. *
  47607. * @abstract
  47608. * @param {Texture} texture - The texture.
  47609. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  47610. */
  47611. destroyTexture( /*texture, isDefaultTexture*/ ) { }
  47612. /**
  47613. * Returns texture data as a typed array.
  47614. *
  47615. * @abstract
  47616. * @async
  47617. * @param {Texture} texture - The texture to copy.
  47618. * @param {number} x - The x coordinate of the copy origin.
  47619. * @param {number} y - The y coordinate of the copy origin.
  47620. * @param {number} width - The width of the copy.
  47621. * @param {number} height - The height of the copy.
  47622. * @param {number} faceIndex - The face index.
  47623. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  47624. */
  47625. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  47626. /**
  47627. * Copies data of the given source texture to the given destination texture.
  47628. *
  47629. * @abstract
  47630. * @param {Texture} srcTexture - The source texture.
  47631. * @param {Texture} dstTexture - The destination texture.
  47632. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  47633. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  47634. * @param {number} [srcLevel=0] - The source mip level to copy from.
  47635. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  47636. */
  47637. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0*/ ) {}
  47638. /**
  47639. * Copies the current bound framebuffer to the given texture.
  47640. *
  47641. * @abstract
  47642. * @param {Texture} texture - The destination texture.
  47643. * @param {RenderContext} renderContext - The render context.
  47644. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  47645. */
  47646. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  47647. // attributes
  47648. /**
  47649. * Creates the GPU buffer of a shader attribute.
  47650. *
  47651. * @abstract
  47652. * @param {BufferAttribute} attribute - The buffer attribute.
  47653. */
  47654. createAttribute( /*attribute*/ ) { }
  47655. /**
  47656. * Creates the GPU buffer of an indexed shader attribute.
  47657. *
  47658. * @abstract
  47659. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  47660. */
  47661. createIndexAttribute( /*attribute*/ ) { }
  47662. /**
  47663. * Creates the GPU buffer of a storage attribute.
  47664. *
  47665. * @abstract
  47666. * @param {BufferAttribute} attribute - The buffer attribute.
  47667. */
  47668. createStorageAttribute( /*attribute*/ ) { }
  47669. /**
  47670. * Creates a uniform buffer.
  47671. *
  47672. * @abstract
  47673. * @param {Buffer} uniformBuffer - The uniform buffer.
  47674. */
  47675. createUniformBuffer( /*uniformBuffer*/ ) { }
  47676. /**
  47677. * Destroys a uniform buffer.
  47678. *
  47679. * @abstract
  47680. * @param {Buffer} uniformBuffer - The uniform buffer.
  47681. */
  47682. destroyUniformBuffer( /*uniformBuffer*/ ) { }
  47683. /**
  47684. * Updates the GPU buffer of a shader attribute.
  47685. *
  47686. * @abstract
  47687. * @param {BufferAttribute} attribute - The buffer attribute to update.
  47688. */
  47689. updateAttribute( /*attribute*/ ) { }
  47690. /**
  47691. * Destroys the GPU buffer of a shader attribute.
  47692. *
  47693. * @abstract
  47694. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  47695. */
  47696. destroyAttribute( /*attribute*/ ) { }
  47697. // canvas
  47698. /**
  47699. * Returns the backend's rendering context.
  47700. *
  47701. * @abstract
  47702. * @return {Object} The rendering context.
  47703. */
  47704. getContext() { }
  47705. /**
  47706. * Backends can use this method if they have to run
  47707. * logic when the renderer gets resized.
  47708. *
  47709. * @abstract
  47710. */
  47711. updateSize() { }
  47712. /**
  47713. * Updates the viewport with the values from the given render context.
  47714. *
  47715. * @abstract
  47716. * @param {RenderContext} renderContext - The render context.
  47717. */
  47718. updateViewport( /*renderContext*/ ) {}
  47719. // utils
  47720. /**
  47721. * Updates a unique identifier for the given render context that can be used
  47722. * to allocate resources like occlusion queries or timestamp queries.
  47723. *
  47724. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  47725. */
  47726. updateTimeStampUID( abstractRenderContext ) {
  47727. const contextData = this.get( abstractRenderContext );
  47728. const frame = this.renderer.info.frame;
  47729. let prefix;
  47730. if ( abstractRenderContext.isComputeNode === true ) {
  47731. prefix = 'c:' + this.renderer.info.compute.frameCalls;
  47732. } else {
  47733. prefix = 'r:' + this.renderer.info.render.frameCalls;
  47734. }
  47735. contextData.timestampUID = prefix + ':' + abstractRenderContext.id + ':f' + frame;
  47736. }
  47737. /**
  47738. * Returns a unique identifier for the given render context that can be used
  47739. * to allocate resources like occlusion queries or timestamp queries.
  47740. *
  47741. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  47742. * @return {string} The unique identifier.
  47743. */
  47744. getTimestampUID( abstractRenderContext ) {
  47745. return this.get( abstractRenderContext ).timestampUID;
  47746. }
  47747. /**
  47748. * Returns all timestamp frames for the given type.
  47749. *
  47750. * @param {string} type - The type of the time stamp.
  47751. * @return {Array<number>} The timestamp frames.
  47752. */
  47753. getTimestampFrames( type ) {
  47754. const queryPool = this.timestampQueryPool[ type ];
  47755. return queryPool ? queryPool.getTimestampFrames() : [];
  47756. }
  47757. /**
  47758. * Returns the query pool for the given uid.
  47759. *
  47760. * @param {string} uid - The unique identifier.
  47761. * @return {TimestampQueryPool} The query pool.
  47762. */
  47763. _getQueryPool( uid ) {
  47764. const type = uid.startsWith( 'c:' ) ? TimestampQuery.COMPUTE : TimestampQuery.RENDER;
  47765. const queryPool = this.timestampQueryPool[ type ];
  47766. return queryPool;
  47767. }
  47768. /**
  47769. * Returns the timestamp for the given uid.
  47770. *
  47771. * @param {string} uid - The unique identifier.
  47772. * @return {number} The timestamp.
  47773. */
  47774. getTimestamp( uid ) {
  47775. const queryPool = this._getQueryPool( uid );
  47776. return queryPool.getTimestamp( uid );
  47777. }
  47778. /**
  47779. * Whether the backend supports query timestamps or not.
  47780. *
  47781. * @type {boolean}
  47782. * @readonly
  47783. */
  47784. get hasTimestamp() {
  47785. return false;
  47786. }
  47787. /**
  47788. * Returns `true` if a timestamp for the given uid is available.
  47789. *
  47790. * @param {string} uid - The unique identifier.
  47791. * @return {boolean} Whether the timestamp is available or not.
  47792. */
  47793. hasTimestampQuery( uid ) {
  47794. const queryPool = this._getQueryPool( uid );
  47795. return queryPool.hasTimestampQuery( uid );
  47796. }
  47797. /**
  47798. * Returns `true` if the given 3D object is fully occluded by other
  47799. * 3D objects in the scene. Backends must implement this method by using
  47800. * a Occlusion Query API.
  47801. *
  47802. * @abstract
  47803. * @param {RenderContext} renderContext - The render context.
  47804. * @param {Object3D} object - The 3D object to test.
  47805. * @return {boolean} Whether the 3D object is fully occluded or not.
  47806. */
  47807. isOccluded( /*renderContext, object*/ ) {}
  47808. /**
  47809. * Resolves the time stamp for the given render context and type.
  47810. *
  47811. * @async
  47812. * @abstract
  47813. * @param {string} [type='render'] - The type of the time stamp.
  47814. * @return {Promise<number>} A Promise that resolves with the time stamp.
  47815. */
  47816. async resolveTimestampsAsync( type = 'render' ) {
  47817. if ( ! this.trackTimestamp ) {
  47818. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  47819. return;
  47820. }
  47821. const queryPool = this.timestampQueryPool[ type ];
  47822. if ( ! queryPool ) {
  47823. return;
  47824. }
  47825. const duration = await queryPool.resolveQueriesAsync();
  47826. this.renderer.info[ type ].timestamp = duration;
  47827. return duration;
  47828. }
  47829. /**
  47830. * This method performs a readback operation by moving buffer data from
  47831. * a storage buffer attribute from the GPU to the CPU.
  47832. *
  47833. * @async
  47834. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  47835. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  47836. */
  47837. async getArrayBufferAsync( /* attribute */ ) {}
  47838. /**
  47839. * Checks if the given feature is supported by the backend.
  47840. *
  47841. * @async
  47842. * @abstract
  47843. * @param {string} name - The feature's name.
  47844. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  47845. */
  47846. async hasFeatureAsync( /*name*/ ) { }
  47847. /**
  47848. * Checks if the given feature is supported by the backend.
  47849. *
  47850. * @abstract
  47851. * @param {string} name - The feature's name.
  47852. * @return {boolean} Whether the feature is supported or not.
  47853. */
  47854. hasFeature( /*name*/ ) {}
  47855. /**
  47856. * Returns the drawing buffer size.
  47857. *
  47858. * @return {Vector2} The drawing buffer size.
  47859. */
  47860. getDrawingBufferSize() {
  47861. _vector2 = _vector2 || new Vector2();
  47862. return this.renderer.getDrawingBufferSize( _vector2 );
  47863. }
  47864. /**
  47865. * Defines the scissor test.
  47866. *
  47867. * @abstract
  47868. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  47869. */
  47870. setScissorTest( /*boolean*/ ) { }
  47871. /**
  47872. * Resets the backend's internal state. A no-op for backends without a state cache (e.g. WebGPU).
  47873. *
  47874. * @abstract
  47875. */
  47876. resetState() { }
  47877. /**
  47878. * Returns the clear color and alpha into a single
  47879. * color object.
  47880. *
  47881. * @return {Color4} The clear color.
  47882. */
  47883. getClearColor() {
  47884. const renderer = this.renderer;
  47885. _color4 = _color4 || new Color4();
  47886. renderer.getClearColor( _color4 );
  47887. _color4.getRGB( _color4 );
  47888. return _color4;
  47889. }
  47890. /**
  47891. * Returns the DOM element. If no DOM element exists, the backend
  47892. * creates a new one.
  47893. *
  47894. * @return {HTMLCanvasElement} The DOM element.
  47895. */
  47896. getDomElement() {
  47897. let domElement = this.domElement;
  47898. if ( domElement === null ) {
  47899. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  47900. // OffscreenCanvas does not have setAttribute, see #22811
  47901. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  47902. this.domElement = domElement;
  47903. }
  47904. return domElement;
  47905. }
  47906. /**
  47907. * Checks if the backend has the given compatibility.
  47908. *
  47909. * @abstract
  47910. * @param {string} name - The compatibility.
  47911. * @return {boolean} Whether the backend has the given compatibility or not.
  47912. */
  47913. hasCompatibility( /*name*/ ) {
  47914. return false;
  47915. }
  47916. /**
  47917. * Initializes the render target defined in the given render context.
  47918. *
  47919. * @abstract
  47920. * @param {RenderContext} renderContext - The render context.
  47921. */
  47922. initRenderTarget( /*renderContext*/ ) {}
  47923. /**
  47924. * Sets a dictionary for the given object into the
  47925. * internal data structure.
  47926. *
  47927. * @param {Object} object - The object.
  47928. * @param {Object} value - The dictionary to set.
  47929. */
  47930. set( object, value ) {
  47931. this.data.set( object, value );
  47932. }
  47933. /**
  47934. * Returns the dictionary for the given object.
  47935. *
  47936. * @param {Object} object - The object.
  47937. * @return {Object} The object's dictionary.
  47938. */
  47939. get( object ) {
  47940. let map = this.data.get( object );
  47941. if ( map === undefined ) {
  47942. map = {};
  47943. this.data.set( object, map );
  47944. }
  47945. return map;
  47946. }
  47947. /**
  47948. * Checks if the given object has a dictionary
  47949. * with data defined.
  47950. *
  47951. * @param {Object} object - The object.
  47952. * @return {boolean} Whether a dictionary for the given object as been defined or not.
  47953. */
  47954. has( object ) {
  47955. return this.data.has( object );
  47956. }
  47957. /**
  47958. * Deletes an object from the internal data structure.
  47959. *
  47960. * @param {Object} object - The object to delete.
  47961. */
  47962. delete( object ) {
  47963. this.data.delete( object );
  47964. }
  47965. /**
  47966. * Delete GPU data associated with a bind group.
  47967. *
  47968. * @abstract
  47969. * @param {BindGroup} bindGroup - The bind group.
  47970. */
  47971. deleteBindGroupData( /*bindGroup*/ ) { }
  47972. /**
  47973. * Frees internal resources.
  47974. *
  47975. * @abstract
  47976. */
  47977. dispose() { }
  47978. }
  47979. let _id$1 = 0;
  47980. /**
  47981. * This module is internally used in context of compute shaders.
  47982. * This type of shader is not natively supported in WebGL 2 and
  47983. * thus implemented via Transform Feedback. `DualAttributeData`
  47984. * manages the related data.
  47985. *
  47986. * @private
  47987. */
  47988. class DualAttributeData {
  47989. constructor( attributeData, dualBuffer ) {
  47990. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  47991. this.type = attributeData.type;
  47992. this.bufferType = attributeData.bufferType;
  47993. this.pbo = attributeData.pbo;
  47994. this.byteLength = attributeData.byteLength;
  47995. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  47996. this.version = attributeData.version;
  47997. this.isInteger = attributeData.isInteger;
  47998. this.activeBufferIndex = 0;
  47999. this.baseId = attributeData.id;
  48000. }
  48001. get id() {
  48002. return `${ this.baseId }|${ this.activeBufferIndex }`;
  48003. }
  48004. get bufferGPU() {
  48005. return this.buffers[ this.activeBufferIndex ];
  48006. }
  48007. get transformBuffer() {
  48008. return this.buffers[ this.activeBufferIndex ^ 1 ];
  48009. }
  48010. switchBuffers() {
  48011. this.activeBufferIndex ^= 1;
  48012. }
  48013. }
  48014. /**
  48015. * A WebGL 2 backend utility module for managing shader attributes.
  48016. *
  48017. * @private
  48018. */
  48019. class WebGLAttributeUtils {
  48020. /**
  48021. * Constructs a new utility object.
  48022. *
  48023. * @param {WebGLBackend} backend - The WebGL 2 backend.
  48024. */
  48025. constructor( backend ) {
  48026. /**
  48027. * A reference to the WebGL 2 backend.
  48028. *
  48029. * @type {WebGLBackend}
  48030. */
  48031. this.backend = backend;
  48032. }
  48033. /**
  48034. * Creates the GPU buffer for the given buffer attribute.
  48035. *
  48036. * @param {BufferAttribute} attribute - The buffer attribute.
  48037. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  48038. */
  48039. createAttribute( attribute, bufferType ) {
  48040. const backend = this.backend;
  48041. const { gl } = backend;
  48042. const array = attribute.array;
  48043. const usage = attribute.usage || gl.STATIC_DRAW;
  48044. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  48045. const bufferData = backend.get( bufferAttribute );
  48046. let bufferGPU = bufferData.bufferGPU;
  48047. if ( bufferGPU === undefined ) {
  48048. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  48049. bufferData.bufferGPU = bufferGPU;
  48050. bufferData.bufferType = bufferType;
  48051. bufferData.version = bufferAttribute.version;
  48052. }
  48053. //attribute.onUploadCallback();
  48054. let type;
  48055. if ( array instanceof Float32Array ) {
  48056. type = gl.FLOAT;
  48057. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  48058. type = gl.HALF_FLOAT;
  48059. } else if ( array instanceof Uint16Array ) {
  48060. if ( attribute.isFloat16BufferAttribute ) {
  48061. type = gl.HALF_FLOAT;
  48062. } else {
  48063. type = gl.UNSIGNED_SHORT;
  48064. }
  48065. } else if ( array instanceof Int16Array ) {
  48066. type = gl.SHORT;
  48067. } else if ( array instanceof Uint32Array ) {
  48068. type = gl.UNSIGNED_INT;
  48069. } else if ( array instanceof Int32Array ) {
  48070. type = gl.INT;
  48071. } else if ( array instanceof Int8Array ) {
  48072. type = gl.BYTE;
  48073. } else if ( array instanceof Uint8Array ) {
  48074. type = gl.UNSIGNED_BYTE;
  48075. } else if ( array instanceof Uint8ClampedArray ) {
  48076. type = gl.UNSIGNED_BYTE;
  48077. } else {
  48078. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  48079. }
  48080. let attributeData = {
  48081. bufferGPU,
  48082. bufferType,
  48083. type,
  48084. byteLength: array.byteLength,
  48085. bytesPerElement: array.BYTES_PER_ELEMENT,
  48086. version: attribute.version,
  48087. pbo: attribute.pbo,
  48088. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  48089. id: _id$1 ++
  48090. };
  48091. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  48092. // create buffer for transform feedback use
  48093. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  48094. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  48095. }
  48096. backend.set( attribute, attributeData );
  48097. }
  48098. /**
  48099. * Updates the GPU buffer of the given buffer attribute.
  48100. *
  48101. * @param {BufferAttribute} attribute - The buffer attribute.
  48102. */
  48103. updateAttribute( attribute ) {
  48104. const backend = this.backend;
  48105. const { gl } = backend;
  48106. const array = attribute.array;
  48107. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  48108. const bufferData = backend.get( bufferAttribute );
  48109. const bufferType = bufferData.bufferType;
  48110. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  48111. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  48112. if ( updateRanges.length === 0 ) {
  48113. // Not using update ranges
  48114. gl.bufferSubData( bufferType, 0, array );
  48115. } else {
  48116. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  48117. const range = updateRanges[ i ];
  48118. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  48119. array, range.start, range.count );
  48120. }
  48121. bufferAttribute.clearUpdateRanges();
  48122. }
  48123. gl.bindBuffer( bufferType, null );
  48124. bufferData.version = bufferAttribute.version;
  48125. }
  48126. /**
  48127. * Destroys the GPU buffer of the given buffer attribute.
  48128. *
  48129. * @param {BufferAttribute} attribute - The buffer attribute.
  48130. */
  48131. destroyAttribute( attribute ) {
  48132. const backend = this.backend;
  48133. const { gl } = backend;
  48134. if ( attribute.isInterleavedBufferAttribute ) {
  48135. backend.delete( attribute.data );
  48136. }
  48137. const attributeData = backend.get( attribute );
  48138. gl.deleteBuffer( attributeData.bufferGPU );
  48139. backend.delete( attribute );
  48140. }
  48141. /**
  48142. * This method performs a readback operation by moving buffer data from
  48143. * a storage buffer attribute from the GPU to the CPU. ReadbackBuffer can
  48144. * be used to retain and reuse handles to the intermediate buffers and prevent
  48145. * new allocation.
  48146. *
  48147. * @async
  48148. * @param {BufferAttribute} attribute - The storage buffer attribute to read frm.
  48149. * @param {ReadbackBuffer|ArrayBuffer} target - The storage buffer attribute.
  48150. * @param {number} offset - The storage buffer attribute.
  48151. * @param {number} count - The offset from which to start reading the
  48152. * @return {Promise<ArrayBuffer|ReadbackBuffer>} A promise that resolves with the buffer data when the data are ready.
  48153. */
  48154. async getArrayBufferAsync( attribute, target = null, offset = 0, count = -1 ) {
  48155. const backend = this.backend;
  48156. const { gl } = backend;
  48157. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  48158. const attributeInfo = backend.get( bufferAttribute );
  48159. const { bufferGPU } = attributeInfo;
  48160. const byteLength = count === -1 ? attributeInfo.byteLength - offset : count;
  48161. // read the data back
  48162. let dstBuffer;
  48163. if ( target === null ) {
  48164. dstBuffer = new Uint8Array( new ArrayBuffer( byteLength ) );
  48165. } else if ( target.isReadbackBuffer ) {
  48166. if ( target._mapped === true ) {
  48167. throw new Error( 'THREE.WebGPURenderer: ReadbackBuffer must be released before being used again.' );
  48168. }
  48169. const releaseCallback = () => {
  48170. target.buffer = null;
  48171. target._mapped = false;
  48172. target.removeEventListener( 'release', releaseCallback );
  48173. target.removeEventListener( 'dispose', releaseCallback );
  48174. };
  48175. target.addEventListener( 'release', releaseCallback );
  48176. target.addEventListener( 'dispose', releaseCallback );
  48177. // WebGL has no concept of a "mapped" data buffer so we create a new buffer, instead.
  48178. dstBuffer = new Uint8Array( new ArrayBuffer( byteLength ) );
  48179. target.buffer = dstBuffer.buffer;
  48180. } else {
  48181. dstBuffer = new Uint8Array( target );
  48182. }
  48183. // Ensure the buffer is bound before reading
  48184. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  48185. gl.getBufferSubData( gl.COPY_READ_BUFFER, offset, dstBuffer );
  48186. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  48187. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  48188. // return the appropriate type
  48189. if ( target && target.isReadbackBuffer ) {
  48190. return target;
  48191. } else {
  48192. return dstBuffer.buffer;
  48193. }
  48194. }
  48195. /**
  48196. * Creates a WebGL buffer with the given data.
  48197. *
  48198. * @private
  48199. * @param {WebGL2RenderingContext} gl - The rendering context.
  48200. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  48201. * @param {TypedArray} array - The array of the buffer attribute.
  48202. * @param {GLenum} usage - The usage.
  48203. * @return {WebGLBuffer} The WebGL buffer.
  48204. */
  48205. _createBuffer( gl, bufferType, array, usage ) {
  48206. const bufferGPU = gl.createBuffer();
  48207. gl.bindBuffer( bufferType, bufferGPU );
  48208. gl.bufferData( bufferType, array, usage );
  48209. gl.bindBuffer( bufferType, null );
  48210. return bufferGPU;
  48211. }
  48212. }
  48213. let equationToGL, factorToGL;
  48214. /**
  48215. * A WebGL 2 backend utility module for managing the WebGL state.
  48216. *
  48217. * The major goal of this module is to reduce the number of state changes
  48218. * by caching the WEbGL state with a series of variables. In this way, the
  48219. * renderer only executes state change commands when necessary which
  48220. * improves the overall performance.
  48221. *
  48222. * @private
  48223. */
  48224. class WebGLState {
  48225. /**
  48226. * Constructs a new utility object.
  48227. *
  48228. * @param {WebGLBackend} backend - The WebGL 2 backend.
  48229. */
  48230. constructor( backend ) {
  48231. /**
  48232. * A reference to the WebGL 2 backend.
  48233. *
  48234. * @type {WebGLBackend}
  48235. */
  48236. this.backend = backend;
  48237. /**
  48238. * A reference to the rendering context.
  48239. *
  48240. * @type {WebGL2RenderingContext}
  48241. */
  48242. this.gl = this.backend.gl;
  48243. // Below properties are intended to cache
  48244. // the WebGL state and are not explicitly
  48245. // documented for convenience reasons.
  48246. this.enabled = {};
  48247. this.parameters = {};
  48248. this.currentFlipSided = null;
  48249. this.currentCullFace = null;
  48250. this.currentProgram = null;
  48251. this.currentBlendingEnabled = false;
  48252. this.currentBlending = null;
  48253. this.currentBlendEquation = null;
  48254. this.currentBlendEquationAlpha = null;
  48255. this.currentBlendSrc = null;
  48256. this.currentBlendDst = null;
  48257. this.currentBlendSrcAlpha = null;
  48258. this.currentBlendDstAlpha = null;
  48259. this.currentPremultipledAlpha = null;
  48260. this.currentPolygonOffsetFactor = null;
  48261. this.currentPolygonOffsetUnits = null;
  48262. this.currentColorMask = null;
  48263. this.currentDepthReversed = false;
  48264. this.currentDepthFunc = null;
  48265. this.currentDepthMask = null;
  48266. this.currentStencilFunc = null;
  48267. this.currentStencilRef = null;
  48268. this.currentStencilFuncMask = null;
  48269. this.currentStencilFail = null;
  48270. this.currentStencilZFail = null;
  48271. this.currentStencilZPass = null;
  48272. this.currentStencilMask = null;
  48273. this.currentLineWidth = null;
  48274. this.currentClippingPlanes = 0;
  48275. this.currentVAO = null;
  48276. this.currentIndex = null;
  48277. this.currentBoundFramebuffers = {};
  48278. this.currentDrawbuffers = new WeakMap();
  48279. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  48280. this.currentTextureSlot = null;
  48281. this.currentBoundTextures = {};
  48282. this.currentBoundBufferBases = {};
  48283. this._init();
  48284. }
  48285. /**
  48286. * Inits the state of the utility.
  48287. *
  48288. * @private
  48289. */
  48290. _init() {
  48291. const gl = this.gl;
  48292. // Store only WebGL constants here.
  48293. equationToGL = {
  48294. [ AddEquation ]: gl.FUNC_ADD,
  48295. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  48296. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  48297. };
  48298. factorToGL = {
  48299. [ ZeroFactor ]: gl.ZERO,
  48300. [ OneFactor ]: gl.ONE,
  48301. [ SrcColorFactor ]: gl.SRC_COLOR,
  48302. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  48303. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  48304. [ DstColorFactor ]: gl.DST_COLOR,
  48305. [ DstAlphaFactor ]: gl.DST_ALPHA,
  48306. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  48307. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  48308. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  48309. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  48310. };
  48311. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  48312. const viewportParam = gl.getParameter( gl.VIEWPORT );
  48313. this.currentScissor = new Vector4().fromArray( scissorParam );
  48314. this.currentViewport = new Vector4().fromArray( viewportParam );
  48315. this._tempVec4 = new Vector4();
  48316. }
  48317. /**
  48318. * Enables the given WebGL capability.
  48319. *
  48320. * This method caches the capability state so
  48321. * `gl.enable()` is only called when necessary.
  48322. *
  48323. * @param {GLenum} id - The capability to enable.
  48324. */
  48325. enable( id ) {
  48326. const { enabled } = this;
  48327. if ( enabled[ id ] !== true ) {
  48328. this.gl.enable( id );
  48329. enabled[ id ] = true;
  48330. }
  48331. }
  48332. /**
  48333. * Disables the given WebGL capability.
  48334. *
  48335. * This method caches the capability state so
  48336. * `gl.disable()` is only called when necessary.
  48337. *
  48338. * @param {GLenum} id - The capability to enable.
  48339. */
  48340. disable( id ) {
  48341. const { enabled } = this;
  48342. if ( enabled[ id ] !== false ) {
  48343. this.gl.disable( id );
  48344. enabled[ id ] = false;
  48345. }
  48346. }
  48347. /**
  48348. * Specifies whether polygons are front- or back-facing
  48349. * by setting the winding orientation.
  48350. *
  48351. * This method caches the state so `gl.frontFace()` is only
  48352. * called when necessary.
  48353. *
  48354. * @param {boolean} flipSided - Whether triangles flipped their sides or not.
  48355. */
  48356. setFlipSided( flipSided ) {
  48357. if ( this.currentFlipSided !== flipSided ) {
  48358. const { gl } = this;
  48359. if ( flipSided ) {
  48360. gl.frontFace( gl.CW );
  48361. } else {
  48362. gl.frontFace( gl.CCW );
  48363. }
  48364. this.currentFlipSided = flipSided;
  48365. }
  48366. }
  48367. /**
  48368. * Specifies whether or not front- and/or back-facing
  48369. * polygons can be culled.
  48370. *
  48371. * This method caches the state so `gl.cullFace()` is only
  48372. * called when necessary.
  48373. *
  48374. * @param {number} cullFace - Defines which polygons are candidates for culling.
  48375. */
  48376. setCullFace( cullFace ) {
  48377. const { gl } = this;
  48378. if ( cullFace !== CullFaceNone ) {
  48379. this.enable( gl.CULL_FACE );
  48380. if ( cullFace !== this.currentCullFace ) {
  48381. if ( cullFace === CullFaceBack ) {
  48382. gl.cullFace( gl.BACK );
  48383. } else if ( cullFace === CullFaceFront ) {
  48384. gl.cullFace( gl.FRONT );
  48385. } else {
  48386. gl.cullFace( gl.FRONT_AND_BACK );
  48387. }
  48388. }
  48389. } else {
  48390. this.disable( gl.CULL_FACE );
  48391. }
  48392. this.currentCullFace = cullFace;
  48393. }
  48394. /**
  48395. * Specifies the width of line primitives.
  48396. *
  48397. * This method caches the state so `gl.lineWidth()` is only
  48398. * called when necessary.
  48399. *
  48400. * @param {number} width - The line width.
  48401. */
  48402. setLineWidth( width ) {
  48403. const { currentLineWidth, gl } = this;
  48404. if ( width !== currentLineWidth ) {
  48405. gl.lineWidth( width );
  48406. this.currentLineWidth = width;
  48407. }
  48408. }
  48409. setMRTBlending( textures, mrt, material ) {
  48410. const gl = this.gl;
  48411. const drawBuffersIndexedExt = this.backend.drawBuffersIndexedExt;
  48412. if ( ! drawBuffersIndexedExt ) {
  48413. warnOnce( 'WebGPURenderer: Multiple Render Targets (MRT) blending configuration is not fully supported in compatibility mode. The material blending will be used for all render targets.' );
  48414. return;
  48415. }
  48416. for ( let i = 0; i < textures.length; i ++ ) {
  48417. const texture = textures[ i ];
  48418. let blending = null;
  48419. if ( mrt !== null ) {
  48420. const blendMode = mrt.getBlendMode( texture.name );
  48421. if ( blendMode.blending === MaterialBlending ) {
  48422. // use material blending
  48423. blending = material;
  48424. } else if ( blendMode.blending !== NoBlending ) {
  48425. blending = blendMode;
  48426. }
  48427. } else {
  48428. // use material blending
  48429. blending = material;
  48430. }
  48431. if ( blending !== null ) {
  48432. this._setMRTBlendingIndex( i, blending );
  48433. } else {
  48434. // use opaque blending (no blending)
  48435. drawBuffersIndexedExt.blendFuncSeparateiOES( i, gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  48436. }
  48437. }
  48438. }
  48439. /**
  48440. * Applies blending configuration for a specific draw buffer index.
  48441. *
  48442. * @private
  48443. * @param {number} index - The draw buffer index.
  48444. * @param {Object} blending - The blending configuration (material or BlendMode).
  48445. */
  48446. _setMRTBlendingIndex( index, blending ) {
  48447. const { gl } = this;
  48448. const drawBuffersIndexedExt = this.backend.drawBuffersIndexedExt;
  48449. const blendingType = blending.blending;
  48450. const blendSrc = blending.blendSrc;
  48451. const blendDst = blending.blendDst;
  48452. const blendEquation = blending.blendEquation;
  48453. const premultipliedAlpha = blending.premultipliedAlpha;
  48454. if ( blendingType === CustomBlending ) {
  48455. const blendSrcAlpha = blending.blendSrcAlpha !== null ? blending.blendSrcAlpha : blendSrc;
  48456. const blendDstAlpha = blending.blendDstAlpha !== null ? blending.blendDstAlpha : blendDst;
  48457. const blendEquationAlpha = blending.blendEquationAlpha !== null ? blending.blendEquationAlpha : blendEquation;
  48458. drawBuffersIndexedExt.blendEquationSeparateiOES( index, equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  48459. drawBuffersIndexedExt.blendFuncSeparateiOES( index, factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  48460. } else {
  48461. drawBuffersIndexedExt.blendEquationSeparateiOES( index, gl.FUNC_ADD, gl.FUNC_ADD );
  48462. if ( premultipliedAlpha ) {
  48463. switch ( blendingType ) {
  48464. case NormalBlending:
  48465. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  48466. break;
  48467. case AdditiveBlending:
  48468. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.ONE, gl.ONE, gl.ONE, gl.ONE );
  48469. break;
  48470. case SubtractiveBlending:
  48471. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  48472. break;
  48473. case MultiplyBlending:
  48474. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  48475. break;
  48476. default:
  48477. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  48478. break;
  48479. }
  48480. } else {
  48481. switch ( blendingType ) {
  48482. case NormalBlending:
  48483. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  48484. break;
  48485. case AdditiveBlending:
  48486. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  48487. break;
  48488. case SubtractiveBlending:
  48489. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  48490. break;
  48491. case MultiplyBlending:
  48492. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  48493. break;
  48494. default:
  48495. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  48496. break;
  48497. }
  48498. }
  48499. }
  48500. }
  48501. /**
  48502. * Defines the blending.
  48503. *
  48504. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  48505. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  48506. *
  48507. * @param {number} blending - The blending type.
  48508. * @param {number} blendEquation - The blending equation.
  48509. * @param {number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  48510. * @param {number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  48511. * @param {number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  48512. * @param {number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  48513. * @param {number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  48514. * @param {boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  48515. */
  48516. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  48517. const { gl } = this;
  48518. if ( blending === NoBlending ) {
  48519. if ( this.currentBlendingEnabled === true ) {
  48520. this.disable( gl.BLEND );
  48521. this.currentBlendingEnabled = false;
  48522. }
  48523. return;
  48524. }
  48525. if ( this.currentBlendingEnabled === false ) {
  48526. this.enable( gl.BLEND );
  48527. this.currentBlendingEnabled = true;
  48528. }
  48529. if ( blending !== CustomBlending ) {
  48530. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  48531. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  48532. gl.blendEquation( gl.FUNC_ADD );
  48533. this.currentBlendEquation = AddEquation;
  48534. this.currentBlendEquationAlpha = AddEquation;
  48535. }
  48536. if ( premultipliedAlpha ) {
  48537. switch ( blending ) {
  48538. case NormalBlending:
  48539. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  48540. break;
  48541. case AdditiveBlending:
  48542. gl.blendFunc( gl.ONE, gl.ONE );
  48543. break;
  48544. case SubtractiveBlending:
  48545. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  48546. break;
  48547. case MultiplyBlending:
  48548. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  48549. break;
  48550. default:
  48551. error( 'WebGLState: Invalid blending: ', blending );
  48552. break;
  48553. }
  48554. } else {
  48555. switch ( blending ) {
  48556. case NormalBlending:
  48557. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  48558. break;
  48559. case AdditiveBlending:
  48560. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  48561. break;
  48562. case SubtractiveBlending:
  48563. error( 'WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  48564. break;
  48565. case MultiplyBlending:
  48566. error( 'WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  48567. break;
  48568. default:
  48569. error( 'WebGLState: Invalid blending: ', blending );
  48570. break;
  48571. }
  48572. }
  48573. this.currentBlendSrc = null;
  48574. this.currentBlendDst = null;
  48575. this.currentBlendSrcAlpha = null;
  48576. this.currentBlendDstAlpha = null;
  48577. this.currentBlending = blending;
  48578. this.currentPremultipledAlpha = premultipliedAlpha;
  48579. }
  48580. return;
  48581. }
  48582. // custom blending
  48583. blendEquationAlpha = blendEquationAlpha || blendEquation;
  48584. blendSrcAlpha = blendSrcAlpha || blendSrc;
  48585. blendDstAlpha = blendDstAlpha || blendDst;
  48586. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  48587. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  48588. this.currentBlendEquation = blendEquation;
  48589. this.currentBlendEquationAlpha = blendEquationAlpha;
  48590. }
  48591. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  48592. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  48593. this.currentBlendSrc = blendSrc;
  48594. this.currentBlendDst = blendDst;
  48595. this.currentBlendSrcAlpha = blendSrcAlpha;
  48596. this.currentBlendDstAlpha = blendDstAlpha;
  48597. }
  48598. this.currentBlending = blending;
  48599. this.currentPremultipledAlpha = false;
  48600. }
  48601. /**
  48602. * Specifies whether colors can be written when rendering
  48603. * into a framebuffer or not.
  48604. *
  48605. * This method caches the state so `gl.colorMask()` is only
  48606. * called when necessary.
  48607. *
  48608. * @param {boolean} colorMask - The color mask.
  48609. */
  48610. setColorMask( colorMask ) {
  48611. if ( this.currentColorMask !== colorMask ) {
  48612. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  48613. this.currentColorMask = colorMask;
  48614. }
  48615. }
  48616. /**
  48617. * Specifies whether the depth test is enabled or not.
  48618. *
  48619. * @param {boolean} depthTest - Whether the depth test is enabled or not.
  48620. */
  48621. setDepthTest( depthTest ) {
  48622. const { gl } = this;
  48623. if ( depthTest ) {
  48624. this.enable( gl.DEPTH_TEST );
  48625. } else {
  48626. this.disable( gl.DEPTH_TEST );
  48627. }
  48628. }
  48629. /**
  48630. * Configures the WebGL state to use a reversed depth buffer.
  48631. *
  48632. * @param {boolean} reversed - Whether the depth buffer is reversed or not.
  48633. */
  48634. setReversedDepth( reversed ) {
  48635. if ( this.currentDepthReversed !== reversed ) {
  48636. const ext = this.backend.extensions.get( 'EXT_clip_control' );
  48637. if ( reversed ) {
  48638. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.ZERO_TO_ONE_EXT );
  48639. } else {
  48640. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.NEGATIVE_ONE_TO_ONE_EXT );
  48641. }
  48642. this.currentDepthReversed = reversed;
  48643. }
  48644. }
  48645. /**
  48646. * Specifies whether depth values can be written when rendering
  48647. * into a framebuffer or not.
  48648. *
  48649. * This method caches the state so `gl.depthMask()` is only
  48650. * called when necessary.
  48651. *
  48652. * @param {boolean} depthMask - The depth mask.
  48653. */
  48654. setDepthMask( depthMask ) {
  48655. if ( this.currentDepthMask !== depthMask ) {
  48656. this.gl.depthMask( depthMask );
  48657. this.currentDepthMask = depthMask;
  48658. }
  48659. }
  48660. /**
  48661. * Specifies the depth compare function.
  48662. *
  48663. * This method caches the state so `gl.depthFunc()` is only
  48664. * called when necessary.
  48665. *
  48666. * @param {number} depthFunc - The depth compare function.
  48667. */
  48668. setDepthFunc( depthFunc ) {
  48669. if ( this.currentDepthReversed ) depthFunc = ReversedDepthFuncs[ depthFunc ];
  48670. if ( this.currentDepthFunc !== depthFunc ) {
  48671. const { gl } = this;
  48672. switch ( depthFunc ) {
  48673. case NeverDepth:
  48674. gl.depthFunc( gl.NEVER );
  48675. break;
  48676. case AlwaysDepth:
  48677. gl.depthFunc( gl.ALWAYS );
  48678. break;
  48679. case LessDepth:
  48680. gl.depthFunc( gl.LESS );
  48681. break;
  48682. case LessEqualDepth:
  48683. gl.depthFunc( gl.LEQUAL );
  48684. break;
  48685. case EqualDepth:
  48686. gl.depthFunc( gl.EQUAL );
  48687. break;
  48688. case GreaterEqualDepth:
  48689. gl.depthFunc( gl.GEQUAL );
  48690. break;
  48691. case GreaterDepth:
  48692. gl.depthFunc( gl.GREATER );
  48693. break;
  48694. case NotEqualDepth:
  48695. gl.depthFunc( gl.NOTEQUAL );
  48696. break;
  48697. default:
  48698. gl.depthFunc( gl.LEQUAL );
  48699. }
  48700. this.currentDepthFunc = depthFunc;
  48701. }
  48702. }
  48703. /**
  48704. * Specifies the scissor box.
  48705. *
  48706. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  48707. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  48708. * @param {number} width - The width of the viewport.
  48709. * @param {number} height - The height of the viewport.
  48710. *
  48711. */
  48712. scissor( x, y, width, height ) {
  48713. const scissor = this._tempVec4.set( x, y, width, height );
  48714. if ( this.currentScissor.equals( scissor ) === false ) {
  48715. const { gl } = this;
  48716. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  48717. this.currentScissor.copy( scissor );
  48718. }
  48719. }
  48720. /**
  48721. * Specifies the viewport.
  48722. *
  48723. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  48724. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  48725. * @param {number} width - The width of the viewport.
  48726. * @param {number} height - The height of the viewport.
  48727. *
  48728. */
  48729. viewport( x, y, width, height ) {
  48730. const viewport = this._tempVec4.set( x, y, width, height );
  48731. if ( this.currentViewport.equals( viewport ) === false ) {
  48732. const { gl } = this;
  48733. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  48734. this.currentViewport.copy( viewport );
  48735. }
  48736. }
  48737. /**
  48738. * Defines the scissor test.
  48739. *
  48740. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  48741. */
  48742. setScissorTest( boolean ) {
  48743. const gl = this.gl;
  48744. if ( boolean ) {
  48745. this.enable( gl.SCISSOR_TEST );
  48746. } else {
  48747. this.disable( gl.SCISSOR_TEST );
  48748. }
  48749. }
  48750. /**
  48751. * Specifies whether the stencil test is enabled or not.
  48752. *
  48753. * @param {boolean} stencilTest - Whether the stencil test is enabled or not.
  48754. */
  48755. setStencilTest( stencilTest ) {
  48756. const { gl } = this;
  48757. if ( stencilTest ) {
  48758. this.enable( gl.STENCIL_TEST );
  48759. } else {
  48760. this.disable( gl.STENCIL_TEST );
  48761. }
  48762. }
  48763. /**
  48764. * Specifies whether stencil values can be written when rendering
  48765. * into a framebuffer or not.
  48766. *
  48767. * This method caches the state so `gl.stencilMask()` is only
  48768. * called when necessary.
  48769. *
  48770. * @param {boolean} stencilMask - The stencil mask.
  48771. */
  48772. setStencilMask( stencilMask ) {
  48773. if ( this.currentStencilMask !== stencilMask ) {
  48774. this.gl.stencilMask( stencilMask );
  48775. this.currentStencilMask = stencilMask;
  48776. }
  48777. }
  48778. /**
  48779. * Specifies whether the stencil test functions.
  48780. *
  48781. * This method caches the state so `gl.stencilFunc()` is only
  48782. * called when necessary.
  48783. *
  48784. * @param {number} stencilFunc - The stencil compare function.
  48785. * @param {number} stencilRef - The reference value for the stencil test.
  48786. * @param {number} stencilMask - A bit-wise mask that is used to AND the reference value and the stored stencil value when the test is done.
  48787. */
  48788. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  48789. if ( this.currentStencilFunc !== stencilFunc ||
  48790. this.currentStencilRef !== stencilRef ||
  48791. this.currentStencilFuncMask !== stencilMask ) {
  48792. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  48793. this.currentStencilFunc = stencilFunc;
  48794. this.currentStencilRef = stencilRef;
  48795. this.currentStencilFuncMask = stencilMask;
  48796. }
  48797. }
  48798. /**
  48799. * Specifies whether the stencil test operation.
  48800. *
  48801. * This method caches the state so `gl.stencilOp()` is only
  48802. * called when necessary.
  48803. *
  48804. * @param {number} stencilFail - The function to use when the stencil test fails.
  48805. * @param {number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  48806. * @param {number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  48807. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  48808. */
  48809. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  48810. if ( this.currentStencilFail !== stencilFail ||
  48811. this.currentStencilZFail !== stencilZFail ||
  48812. this.currentStencilZPass !== stencilZPass ) {
  48813. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  48814. this.currentStencilFail = stencilFail;
  48815. this.currentStencilZFail = stencilZFail;
  48816. this.currentStencilZPass = stencilZPass;
  48817. }
  48818. }
  48819. /**
  48820. * Configures the WebGL state for the given material.
  48821. *
  48822. * @param {Material} material - The material to configure the state for.
  48823. * @param {number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  48824. * @param {number} hardwareClippingPlanes - The number of hardware clipping planes.
  48825. */
  48826. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  48827. const { gl } = this;
  48828. material.side === DoubleSide
  48829. ? this.disable( gl.CULL_FACE )
  48830. : this.enable( gl.CULL_FACE );
  48831. let flipSided = ( material.side === BackSide );
  48832. if ( frontFaceCW ) flipSided = ! flipSided;
  48833. this.setFlipSided( flipSided );
  48834. ( material.blending === NormalBlending && material.transparent === false )
  48835. ? this.setBlending( NoBlending )
  48836. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  48837. this.setDepthFunc( material.depthFunc );
  48838. this.setDepthTest( material.depthTest );
  48839. this.setDepthMask( material.depthWrite );
  48840. this.setColorMask( material.colorWrite );
  48841. const stencilWrite = material.stencilWrite;
  48842. this.setStencilTest( stencilWrite );
  48843. if ( stencilWrite ) {
  48844. this.setStencilMask( material.stencilWriteMask );
  48845. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  48846. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  48847. }
  48848. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  48849. material.alphaToCoverage === true && this.backend.renderer.currentSamples > 0
  48850. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  48851. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  48852. if ( hardwareClippingPlanes > 0 ) {
  48853. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  48854. const CLIP_DISTANCE0_WEBGL = 0x3000;
  48855. for ( let i = 0; i < 8; i ++ ) {
  48856. if ( i < hardwareClippingPlanes ) {
  48857. this.enable( CLIP_DISTANCE0_WEBGL + i );
  48858. } else {
  48859. this.disable( CLIP_DISTANCE0_WEBGL + i );
  48860. }
  48861. }
  48862. }
  48863. }
  48864. }
  48865. /**
  48866. * Specifies the polygon offset.
  48867. *
  48868. * This method caches the state so `gl.polygonOffset()` is only
  48869. * called when necessary.
  48870. *
  48871. * @param {boolean} polygonOffset - Whether polygon offset is enabled or not.
  48872. * @param {number} factor - The scale factor for the variable depth offset for each polygon.
  48873. * @param {number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  48874. */
  48875. setPolygonOffset( polygonOffset, factor, units ) {
  48876. const { gl } = this;
  48877. if ( polygonOffset ) {
  48878. this.enable( gl.POLYGON_OFFSET_FILL );
  48879. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  48880. gl.polygonOffset( factor, units );
  48881. this.currentPolygonOffsetFactor = factor;
  48882. this.currentPolygonOffsetUnits = units;
  48883. }
  48884. } else {
  48885. this.disable( gl.POLYGON_OFFSET_FILL );
  48886. }
  48887. }
  48888. /**
  48889. * Defines the usage of the given WebGL program.
  48890. *
  48891. * This method caches the state so `gl.useProgram()` is only
  48892. * called when necessary.
  48893. *
  48894. * @param {WebGLProgram} program - The WebGL program to use.
  48895. * @return {boolean} Whether a program change has been executed or not.
  48896. */
  48897. useProgram( program ) {
  48898. if ( this.currentProgram !== program ) {
  48899. this.gl.useProgram( program );
  48900. this.currentProgram = program;
  48901. return true;
  48902. }
  48903. return false;
  48904. }
  48905. /**
  48906. * Sets the vertex state by binding the given VAO and element buffer.
  48907. *
  48908. * @param {WebGLVertexArrayObject} vao - The VAO.
  48909. * @param {?WebGLBuffer} indexBuffer - The index buffer.
  48910. * @return {boolean} Whether a vertex state has been changed or not.
  48911. */
  48912. setVertexState( vao, indexBuffer = null ) {
  48913. const gl = this.gl;
  48914. if ( this.currentVAO !== vao || this.currentIndex !== indexBuffer ) {
  48915. gl.bindVertexArray( vao );
  48916. if ( indexBuffer !== null ) {
  48917. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexBuffer );
  48918. }
  48919. this.currentVAO = vao;
  48920. this.currentIndex = indexBuffer;
  48921. return true;
  48922. }
  48923. return false;
  48924. }
  48925. /**
  48926. * Resets the vertex array state by resetting the VAO and element buffer.
  48927. */
  48928. resetVertexState() {
  48929. const gl = this.gl;
  48930. gl.bindVertexArray( null );
  48931. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
  48932. this.currentVAO = null;
  48933. this.currentIndex = null;
  48934. }
  48935. // framebuffer
  48936. /**
  48937. * Binds the given framebuffer.
  48938. *
  48939. * This method caches the state so `gl.bindFramebuffer()` is only
  48940. * called when necessary.
  48941. *
  48942. * @param {number} target - The binding point (target).
  48943. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  48944. * @return {boolean} Whether a bind has been executed or not.
  48945. */
  48946. bindFramebuffer( target, framebuffer ) {
  48947. const { gl, currentBoundFramebuffers } = this;
  48948. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  48949. gl.bindFramebuffer( target, framebuffer );
  48950. currentBoundFramebuffers[ target ] = framebuffer;
  48951. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  48952. if ( target === gl.DRAW_FRAMEBUFFER ) {
  48953. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  48954. }
  48955. if ( target === gl.FRAMEBUFFER ) {
  48956. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  48957. }
  48958. return true;
  48959. }
  48960. return false;
  48961. }
  48962. /**
  48963. * Defines draw buffers to which fragment colors are written into.
  48964. * Configures the MRT setup of custom framebuffers.
  48965. *
  48966. * This method caches the state so `gl.drawBuffers()` is only
  48967. * called when necessary.
  48968. *
  48969. * @param {RenderContext} renderContext - The render context.
  48970. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  48971. */
  48972. drawBuffers( renderContext, framebuffer ) {
  48973. const { gl } = this;
  48974. let drawBuffers = [];
  48975. let needsUpdate = false;
  48976. if ( renderContext.textures !== null ) {
  48977. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  48978. if ( drawBuffers === undefined ) {
  48979. drawBuffers = [];
  48980. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  48981. }
  48982. const textures = renderContext.textures;
  48983. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  48984. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  48985. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  48986. }
  48987. drawBuffers.length = textures.length;
  48988. needsUpdate = true;
  48989. }
  48990. } else {
  48991. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  48992. drawBuffers[ 0 ] = gl.BACK;
  48993. needsUpdate = true;
  48994. }
  48995. }
  48996. if ( needsUpdate ) {
  48997. gl.drawBuffers( drawBuffers );
  48998. }
  48999. }
  49000. // texture
  49001. /**
  49002. * Makes the given texture unit active.
  49003. *
  49004. * This method caches the state so `gl.activeTexture()` is only
  49005. * called when necessary.
  49006. *
  49007. * @param {number} webglSlot - The texture unit to make active.
  49008. */
  49009. activeTexture( webglSlot ) {
  49010. const { gl, currentTextureSlot, maxTextures } = this;
  49011. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  49012. if ( currentTextureSlot !== webglSlot ) {
  49013. gl.activeTexture( webglSlot );
  49014. this.currentTextureSlot = webglSlot;
  49015. }
  49016. }
  49017. /**
  49018. * Binds the given WebGL texture to a target.
  49019. *
  49020. * This method caches the state so `gl.bindTexture()` is only
  49021. * called when necessary.
  49022. *
  49023. * @param {number} webglType - The binding point (target).
  49024. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  49025. * @param {number} webglSlot - The texture.
  49026. */
  49027. bindTexture( webglType, webglTexture, webglSlot ) {
  49028. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  49029. if ( webglSlot === undefined ) {
  49030. if ( currentTextureSlot === null ) {
  49031. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  49032. } else {
  49033. webglSlot = currentTextureSlot;
  49034. }
  49035. }
  49036. let boundTexture = currentBoundTextures[ webglSlot ];
  49037. if ( boundTexture === undefined ) {
  49038. boundTexture = { type: undefined, texture: undefined };
  49039. currentBoundTextures[ webglSlot ] = boundTexture;
  49040. }
  49041. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  49042. if ( currentTextureSlot !== webglSlot ) {
  49043. gl.activeTexture( webglSlot );
  49044. this.currentTextureSlot = webglSlot;
  49045. }
  49046. gl.bindTexture( webglType, webglTexture );
  49047. boundTexture.type = webglType;
  49048. boundTexture.texture = webglTexture;
  49049. }
  49050. }
  49051. /**
  49052. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  49053. *
  49054. * This method caches the state so `gl.bindBufferBase()` is only
  49055. * called when necessary.
  49056. *
  49057. * @param {number} target - The target for the bind operation.
  49058. * @param {number} index - The index of the target.
  49059. * @param {WebGLBuffer} buffer - The WebGL buffer.
  49060. * @return {boolean} Whether a bind has been executed or not.
  49061. */
  49062. bindBufferBase( target, index, buffer ) {
  49063. const { gl } = this;
  49064. const key = `${target}-${index}`;
  49065. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  49066. gl.bindBufferBase( target, index, buffer );
  49067. this.currentBoundBufferBases[ key ] = buffer;
  49068. return true;
  49069. }
  49070. return false;
  49071. }
  49072. /**
  49073. * Unbinds the current bound texture.
  49074. *
  49075. * This method caches the state so `gl.bindTexture()` is only
  49076. * called when necessary.
  49077. */
  49078. unbindTexture() {
  49079. const { gl, currentTextureSlot, currentBoundTextures } = this;
  49080. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  49081. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  49082. gl.bindTexture( boundTexture.type, null );
  49083. boundTexture.type = undefined;
  49084. boundTexture.texture = undefined;
  49085. }
  49086. }
  49087. /**
  49088. * Returns the value for the given parameter.
  49089. *
  49090. * @param {number} name - The paramter to get the value for.
  49091. * @return {any} The value for the given parameter.
  49092. */
  49093. getParameter( name ) {
  49094. const { gl, parameters } = this;
  49095. if ( parameters[ name ] !== undefined ) {
  49096. return parameters[ name ];
  49097. } else {
  49098. return gl.getParameter( name );
  49099. }
  49100. }
  49101. /**
  49102. * Specifies a pixel storage mode.
  49103. *
  49104. * @param {number} name - The parameter to set.
  49105. * @param {any} value - A value to set the parameter to.
  49106. */
  49107. pixelStorei( name, value ) {
  49108. const { gl, parameters } = this;
  49109. if ( parameters[ name ] !== value ) {
  49110. gl.pixelStorei( name, value );
  49111. parameters[ name ] = value;
  49112. }
  49113. }
  49114. /**
  49115. * Restores the WebGL state to its default and clears the cache so subsequent renderings
  49116. * re-apply the required state. Useful when the WebGL context is shared with other libraries.
  49117. */
  49118. reset() {
  49119. const { gl } = this;
  49120. // reset WebGL state
  49121. gl.disable( gl.BLEND );
  49122. gl.disable( gl.CULL_FACE );
  49123. gl.disable( gl.DEPTH_TEST );
  49124. gl.disable( gl.POLYGON_OFFSET_FILL );
  49125. gl.disable( gl.SCISSOR_TEST );
  49126. gl.disable( gl.STENCIL_TEST );
  49127. gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  49128. gl.blendEquation( gl.FUNC_ADD );
  49129. gl.blendFunc( gl.ONE, gl.ZERO );
  49130. gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  49131. gl.blendColor( 0, 0, 0, 0 );
  49132. gl.colorMask( true, true, true, true );
  49133. gl.clearColor( 0, 0, 0, 0 );
  49134. gl.depthMask( true );
  49135. gl.depthFunc( gl.LESS );
  49136. gl.clearDepth( 1 );
  49137. gl.stencilMask( 0xffffffff );
  49138. gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );
  49139. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  49140. gl.clearStencil( 0 );
  49141. gl.cullFace( gl.BACK );
  49142. gl.frontFace( gl.CCW );
  49143. gl.polygonOffset( 0, 0 );
  49144. gl.activeTexture( gl.TEXTURE0 );
  49145. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  49146. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  49147. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  49148. gl.useProgram( null );
  49149. gl.lineWidth( 1 );
  49150. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  49151. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  49152. gl.pixelStorei( gl.PACK_ALIGNMENT, 4 );
  49153. gl.pixelStorei( gl.UNPACK_ALIGNMENT, 4 );
  49154. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  49155. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  49156. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.BROWSER_DEFAULT_WEBGL );
  49157. gl.pixelStorei( gl.PACK_ROW_LENGTH, 0 );
  49158. gl.pixelStorei( gl.PACK_SKIP_PIXELS, 0 );
  49159. gl.pixelStorei( gl.PACK_SKIP_ROWS, 0 );
  49160. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, 0 );
  49161. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, 0 );
  49162. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, 0 );
  49163. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, 0 );
  49164. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, 0 );
  49165. this.resetVertexState();
  49166. // reset internal cache
  49167. this.enabled = {};
  49168. this.parameters = {};
  49169. this.currentFlipSided = null;
  49170. this.currentCullFace = null;
  49171. this.currentProgram = null;
  49172. this.currentBlendingEnabled = false;
  49173. this.currentBlending = null;
  49174. this.currentBlendEquation = null;
  49175. this.currentBlendEquationAlpha = null;
  49176. this.currentBlendSrc = null;
  49177. this.currentBlendDst = null;
  49178. this.currentBlendSrcAlpha = null;
  49179. this.currentBlendDstAlpha = null;
  49180. this.currentPremultipledAlpha = null;
  49181. this.currentPolygonOffsetFactor = null;
  49182. this.currentPolygonOffsetUnits = null;
  49183. this.currentColorMask = null;
  49184. this.currentDepthFunc = null;
  49185. this.currentDepthMask = null;
  49186. this.currentStencilFunc = null;
  49187. this.currentStencilRef = null;
  49188. this.currentStencilFuncMask = null;
  49189. this.currentStencilFail = null;
  49190. this.currentStencilZFail = null;
  49191. this.currentStencilZPass = null;
  49192. this.currentStencilMask = null;
  49193. this.currentLineWidth = null;
  49194. this.currentClippingPlanes = 0;
  49195. this.currentBoundFramebuffers = {};
  49196. this.currentDrawbuffers = new WeakMap();
  49197. this.currentTextureSlot = null;
  49198. this.currentBoundTextures = {};
  49199. this.currentBoundBufferBases = {};
  49200. this.currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  49201. this.currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  49202. // re-apply reversed depth if used by the renderer
  49203. this.currentDepthReversed = false;
  49204. if ( this.backend.renderer.reversedDepthBuffer === true ) {
  49205. this.setReversedDepth( true );
  49206. }
  49207. }
  49208. }
  49209. /**
  49210. * A WebGL 2 backend utility module with common helpers.
  49211. *
  49212. * @private
  49213. */
  49214. class WebGLUtils {
  49215. /**
  49216. * Constructs a new utility object.
  49217. *
  49218. * @param {WebGLBackend} backend - The WebGL 2 backend.
  49219. */
  49220. constructor( backend ) {
  49221. /**
  49222. * A reference to the WebGL 2 backend.
  49223. *
  49224. * @type {WebGLBackend}
  49225. */
  49226. this.backend = backend;
  49227. /**
  49228. * A reference to the rendering context.
  49229. *
  49230. * @type {WebGL2RenderingContext}
  49231. */
  49232. this.gl = this.backend.gl;
  49233. /**
  49234. * A reference to a backend module holding extension-related
  49235. * utility functions.
  49236. *
  49237. * @type {WebGLExtensions}
  49238. */
  49239. this.extensions = backend.extensions;
  49240. }
  49241. /**
  49242. * Converts the given three.js constant into a WebGL constant.
  49243. * The method currently supports the conversion of texture formats
  49244. * and types.
  49245. *
  49246. * @param {number} p - The three.js constant.
  49247. * @param {string} [colorSpace=NoColorSpace] - The color space.
  49248. * @return {?number} The corresponding WebGL constant.
  49249. */
  49250. convert( p, colorSpace = NoColorSpace ) {
  49251. const { gl, extensions } = this;
  49252. let extension;
  49253. const transfer = ColorManagement.getTransfer( colorSpace );
  49254. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  49255. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  49256. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  49257. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  49258. if ( p === UnsignedInt101111Type ) return gl.UNSIGNED_INT_10F_11F_11F_REV;
  49259. if ( p === ByteType ) return gl.BYTE;
  49260. if ( p === ShortType ) return gl.SHORT;
  49261. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  49262. if ( p === IntType ) return gl.INT;
  49263. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  49264. if ( p === FloatType ) return gl.FLOAT;
  49265. if ( p === HalfFloatType ) {
  49266. return gl.HALF_FLOAT;
  49267. }
  49268. if ( p === AlphaFormat ) return gl.ALPHA;
  49269. if ( p === RGBFormat ) return gl.RGB;
  49270. if ( p === RGBAFormat ) return gl.RGBA;
  49271. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  49272. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  49273. // WebGL2 formats.
  49274. if ( p === RedFormat ) return gl.RED;
  49275. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  49276. if ( p === RGFormat ) return gl.RG;
  49277. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  49278. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  49279. // S3TC
  49280. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  49281. if ( transfer === SRGBTransfer ) {
  49282. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  49283. if ( extension !== null ) {
  49284. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  49285. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  49286. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  49287. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  49288. } else {
  49289. return null;
  49290. }
  49291. } else {
  49292. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  49293. if ( extension !== null ) {
  49294. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  49295. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  49296. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  49297. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  49298. } else {
  49299. return null;
  49300. }
  49301. }
  49302. }
  49303. // PVRTC
  49304. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  49305. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  49306. if ( extension !== null ) {
  49307. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  49308. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  49309. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  49310. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  49311. } else {
  49312. return null;
  49313. }
  49314. }
  49315. // ETC
  49316. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format || p === R11_EAC_Format || p === SIGNED_R11_EAC_Format || p === RG11_EAC_Format || p === SIGNED_RG11_EAC_Format ) {
  49317. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  49318. if ( extension !== null ) {
  49319. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  49320. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  49321. if ( p === R11_EAC_Format ) return extension.COMPRESSED_R11_EAC;
  49322. if ( p === SIGNED_R11_EAC_Format ) return extension.COMPRESSED_SIGNED_R11_EAC;
  49323. if ( p === RG11_EAC_Format ) return extension.COMPRESSED_RG11_EAC;
  49324. if ( p === SIGNED_RG11_EAC_Format ) return extension.COMPRESSED_SIGNED_RG11_EAC;
  49325. } else {
  49326. return null;
  49327. }
  49328. }
  49329. // ASTC
  49330. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  49331. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  49332. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  49333. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  49334. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  49335. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  49336. if ( extension !== null ) {
  49337. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  49338. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  49339. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  49340. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  49341. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  49342. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  49343. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  49344. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  49345. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  49346. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  49347. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  49348. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  49349. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  49350. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  49351. } else {
  49352. return null;
  49353. }
  49354. }
  49355. // BPTC
  49356. if ( p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format ) {
  49357. extension = extensions.get( 'EXT_texture_compression_bptc' );
  49358. if ( extension !== null ) {
  49359. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  49360. if ( p === RGB_BPTC_SIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;
  49361. if ( p === RGB_BPTC_UNSIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
  49362. } else {
  49363. return null;
  49364. }
  49365. }
  49366. // RGTC
  49367. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  49368. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  49369. if ( extension !== null ) {
  49370. if ( p === RED_RGTC1_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  49371. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  49372. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  49373. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  49374. } else {
  49375. return null;
  49376. }
  49377. }
  49378. //
  49379. if ( p === UnsignedInt248Type ) {
  49380. return gl.UNSIGNED_INT_24_8;
  49381. }
  49382. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  49383. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  49384. }
  49385. /**
  49386. * This method can be used to synchronize the CPU with the GPU by waiting until
  49387. * ongoing GPU commands have been completed.
  49388. *
  49389. * @private
  49390. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  49391. */
  49392. _clientWaitAsync() {
  49393. const { gl } = this;
  49394. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  49395. gl.flush();
  49396. return new Promise( ( resolve, reject ) => {
  49397. function test() {
  49398. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  49399. if ( res === gl.WAIT_FAILED ) {
  49400. gl.deleteSync( sync );
  49401. reject();
  49402. return;
  49403. }
  49404. if ( res === gl.TIMEOUT_EXPIRED ) {
  49405. requestAnimationFrame( test );
  49406. return;
  49407. }
  49408. gl.deleteSync( sync );
  49409. resolve();
  49410. }
  49411. test();
  49412. } );
  49413. }
  49414. }
  49415. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  49416. /**
  49417. * A WebGL 2 backend utility module for managing textures.
  49418. *
  49419. * @private
  49420. */
  49421. class WebGLTextureUtils {
  49422. /**
  49423. * Constructs a new utility object.
  49424. *
  49425. * @param {WebGLBackend} backend - The WebGL 2 backend.
  49426. */
  49427. constructor( backend ) {
  49428. /**
  49429. * A reference to the WebGL 2 backend.
  49430. *
  49431. * @type {WebGLBackend}
  49432. */
  49433. this.backend = backend;
  49434. /**
  49435. * A reference to the rendering context.
  49436. *
  49437. * @type {WebGL2RenderingContext}
  49438. */
  49439. this.gl = backend.gl;
  49440. /**
  49441. * A reference to a backend module holding extension-related
  49442. * utility functions.
  49443. *
  49444. * @type {WebGLExtensions}
  49445. */
  49446. this.extensions = backend.extensions;
  49447. /**
  49448. * A dictionary for managing default textures. The key
  49449. * is the binding point (target), the value the WEbGL texture object.
  49450. *
  49451. * @type {Object<GLenum,WebGLTexture>}
  49452. */
  49453. this.defaultTextures = {};
  49454. /**
  49455. * A scratch framebuffer used for attaching the source texture in
  49456. * {@link copyTextureToTexture}.
  49457. *
  49458. * @private
  49459. * @type {?WebGLFramebuffer}
  49460. */
  49461. this._srcFramebuffer = null;
  49462. /**
  49463. * A scratch framebuffer used for attaching the destination texture in
  49464. * {@link copyTextureToTexture}.
  49465. *
  49466. * @private
  49467. * @type {?WebGLFramebuffer}
  49468. */
  49469. this._dstFramebuffer = null;
  49470. if ( initialized === false ) {
  49471. this._init();
  49472. initialized = true;
  49473. }
  49474. }
  49475. /**
  49476. * Inits the state of the utility.
  49477. *
  49478. * @private
  49479. */
  49480. _init() {
  49481. const gl = this.gl;
  49482. // Store only WebGL constants here.
  49483. wrappingToGL = {
  49484. [ RepeatWrapping ]: gl.REPEAT,
  49485. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  49486. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  49487. };
  49488. filterToGL = {
  49489. [ NearestFilter ]: gl.NEAREST,
  49490. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  49491. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  49492. [ LinearFilter ]: gl.LINEAR,
  49493. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  49494. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  49495. };
  49496. compareToGL = {
  49497. [ NeverCompare ]: gl.NEVER,
  49498. [ AlwaysCompare ]: gl.ALWAYS,
  49499. [ LessCompare ]: gl.LESS,
  49500. [ LessEqualCompare ]: gl.LEQUAL,
  49501. [ EqualCompare ]: gl.EQUAL,
  49502. [ GreaterEqualCompare ]: gl.GEQUAL,
  49503. [ GreaterCompare ]: gl.GREATER,
  49504. [ NotEqualCompare ]: gl.NOTEQUAL
  49505. };
  49506. }
  49507. /**
  49508. * Returns the native texture type for the given texture.
  49509. *
  49510. * @param {Texture} texture - The texture.
  49511. * @return {GLenum} The native texture type.
  49512. */
  49513. getGLTextureType( texture ) {
  49514. const { gl } = this;
  49515. let glTextureType;
  49516. if ( texture.isCubeTexture === true ) {
  49517. glTextureType = gl.TEXTURE_CUBE_MAP;
  49518. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  49519. glTextureType = gl.TEXTURE_2D_ARRAY;
  49520. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  49521. glTextureType = gl.TEXTURE_3D;
  49522. } else {
  49523. glTextureType = gl.TEXTURE_2D;
  49524. }
  49525. return glTextureType;
  49526. }
  49527. /**
  49528. * Returns the native texture type for the given texture.
  49529. *
  49530. * @param {?string} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  49531. * @param {GLenum} glFormat - The WebGL format.
  49532. * @param {GLenum} glType - The WebGL type.
  49533. * @param {string} colorSpace - The texture's color space.
  49534. * @param {boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  49535. * @return {GLenum} The internal format.
  49536. */
  49537. getInternalFormat( internalFormatName, glFormat, glType, normalized, colorSpace, forceLinearTransfer = false ) {
  49538. const { gl, extensions } = this;
  49539. if ( internalFormatName !== null ) {
  49540. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  49541. warn( 'WebGLBackend: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  49542. }
  49543. let extTextureNorm16 = null;
  49544. if ( normalized ) {
  49545. extTextureNorm16 = extensions.get( 'EXT_texture_norm16' );
  49546. if ( ! extTextureNorm16 ) {
  49547. warn( 'WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension' );
  49548. }
  49549. }
  49550. let internalFormat = glFormat;
  49551. if ( glFormat === gl.RED ) {
  49552. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  49553. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  49554. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  49555. if ( glType === gl.BYTE ) internalFormat = gl.R8_SNORM;
  49556. if ( glType === gl.UNSIGNED_SHORT && extTextureNorm16 ) internalFormat = extTextureNorm16.R16_EXT;
  49557. if ( glType === gl.SHORT && extTextureNorm16 ) internalFormat = extTextureNorm16.R16_SNORM_EXT;
  49558. }
  49559. if ( glFormat === gl.RED_INTEGER ) {
  49560. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  49561. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  49562. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  49563. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  49564. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  49565. if ( glType === gl.INT ) internalFormat = gl.R32I;
  49566. }
  49567. if ( glFormat === gl.RG ) {
  49568. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  49569. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  49570. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  49571. if ( glType === gl.BYTE ) internalFormat = gl.RG8_SNORM;
  49572. if ( glType === gl.UNSIGNED_SHORT && extTextureNorm16 ) internalFormat = extTextureNorm16.RG16_EXT;
  49573. if ( glType === gl.SHORT && extTextureNorm16 ) internalFormat = extTextureNorm16.RG16_SNORM_EXT;
  49574. }
  49575. if ( glFormat === gl.RG_INTEGER ) {
  49576. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  49577. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  49578. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  49579. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  49580. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  49581. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  49582. }
  49583. if ( glFormat === gl.RGB ) {
  49584. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  49585. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  49586. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  49587. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8 : gl.RGB8;
  49588. if ( glType === gl.BYTE ) internalFormat = gl.RGB8_SNORM;
  49589. if ( glType === gl.UNSIGNED_SHORT && extTextureNorm16 ) internalFormat = extTextureNorm16.RGB16_EXT;
  49590. if ( glType === gl.SHORT && extTextureNorm16 ) internalFormat = extTextureNorm16.RGB16_SNORM_EXT;
  49591. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  49592. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  49593. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  49594. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  49595. if ( glType === gl.UNSIGNED_INT_10F_11F_11F_REV ) internalFormat = gl.R11F_G11F_B10F;
  49596. }
  49597. if ( glFormat === gl.RGB_INTEGER ) {
  49598. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  49599. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  49600. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  49601. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  49602. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  49603. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  49604. }
  49605. if ( glFormat === gl.RGBA ) {
  49606. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  49607. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  49608. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  49609. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  49610. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8_SNORM;
  49611. if ( glType === gl.UNSIGNED_SHORT && extTextureNorm16 ) internalFormat = extTextureNorm16.RGBA16_EXT;
  49612. if ( glType === gl.SHORT && extTextureNorm16 ) internalFormat = extTextureNorm16.RGBA16_SNORM_EXT;
  49613. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  49614. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  49615. }
  49616. if ( glFormat === gl.RGBA_INTEGER ) {
  49617. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  49618. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  49619. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  49620. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  49621. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  49622. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  49623. }
  49624. if ( glFormat === gl.DEPTH_COMPONENT ) {
  49625. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.DEPTH_COMPONENT16;
  49626. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH_COMPONENT24;
  49627. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  49628. }
  49629. if ( glFormat === gl.DEPTH_STENCIL ) {
  49630. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  49631. }
  49632. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  49633. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  49634. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  49635. extensions.get( 'EXT_color_buffer_float' );
  49636. }
  49637. return internalFormat;
  49638. }
  49639. /**
  49640. * Sets the texture parameters for the given texture.
  49641. *
  49642. * @param {GLenum} textureType - The texture type.
  49643. * @param {Texture} texture - The texture.
  49644. */
  49645. setTextureParameters( textureType, texture ) {
  49646. const { gl, extensions, backend } = this;
  49647. const { state } = this.backend;
  49648. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  49649. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  49650. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? gl.NONE : gl.BROWSER_DEFAULT_WEBGL;
  49651. state.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  49652. state.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  49653. state.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  49654. state.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  49655. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  49656. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  49657. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  49658. // WebGL 2 does not support wrapping for depth 2D array textures
  49659. if ( ! texture.isArrayTexture ) {
  49660. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  49661. }
  49662. }
  49663. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  49664. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  49665. // follow WebGPU backend mapping for texture filtering
  49666. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  49667. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  49668. if ( texture.compareFunction ) {
  49669. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  49670. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  49671. }
  49672. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  49673. if ( texture.magFilter === NearestFilter ) return;
  49674. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  49675. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  49676. if ( texture.anisotropy > 1 ) {
  49677. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  49678. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.capabilities.getMaxAnisotropy() ) );
  49679. }
  49680. }
  49681. }
  49682. /**
  49683. * Creates a default texture for the given texture that can be used
  49684. * as a placeholder until the actual texture is ready for usage.
  49685. *
  49686. * @param {Texture} texture - The texture to create a default texture for.
  49687. */
  49688. createDefaultTexture( texture ) {
  49689. const { gl, backend, defaultTextures } = this;
  49690. const glTextureType = this.getGLTextureType( texture );
  49691. let textureGPU = defaultTextures[ glTextureType ];
  49692. if ( textureGPU === undefined ) {
  49693. textureGPU = gl.createTexture();
  49694. backend.state.bindTexture( glTextureType, textureGPU );
  49695. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  49696. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  49697. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  49698. defaultTextures[ glTextureType ] = textureGPU;
  49699. }
  49700. backend.set( texture, {
  49701. textureGPU,
  49702. glTextureType
  49703. } );
  49704. }
  49705. /**
  49706. * Defines a texture on the GPU for the given texture object.
  49707. *
  49708. * @param {Texture} texture - The texture.
  49709. * @param {Object} [options={}] - Optional configuration parameter.
  49710. * @return {undefined}
  49711. */
  49712. createTexture( texture, options ) {
  49713. const { gl, backend } = this;
  49714. let textureGPU, glTextureType, glFormat, glType, glInternalFormat;
  49715. if ( texture.isExternalTexture === true ) {
  49716. textureGPU = texture.sourceTexture;
  49717. glTextureType = this.getGLTextureType( texture );
  49718. } else {
  49719. const { levels, width, height, depth } = options;
  49720. glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  49721. glType = backend.utils.convert( texture.type );
  49722. glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.normalized, texture.colorSpace, texture.isVideoTexture );
  49723. textureGPU = gl.createTexture();
  49724. glTextureType = this.getGLTextureType( texture );
  49725. backend.state.bindTexture( glTextureType, textureGPU );
  49726. this.setTextureParameters( glTextureType, texture );
  49727. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  49728. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  49729. } else if ( texture.isData3DTexture ) {
  49730. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  49731. } else if ( ! texture.isVideoTexture ) {
  49732. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  49733. }
  49734. }
  49735. backend.set( texture, {
  49736. textureGPU,
  49737. glTextureType,
  49738. glFormat,
  49739. glType,
  49740. glInternalFormat
  49741. } );
  49742. }
  49743. /**
  49744. * Uploads texture buffer data to the GPU memory.
  49745. *
  49746. * @param {WebGLBuffer} buffer - The buffer data.
  49747. * @param {Texture} texture - The texture,
  49748. */
  49749. copyBufferToTexture( buffer, texture ) {
  49750. const { gl, backend } = this;
  49751. const { state } = backend;
  49752. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  49753. const { width, height } = texture.source.data;
  49754. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  49755. backend.state.bindTexture( glTextureType, textureGPU );
  49756. state.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  49757. state.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  49758. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  49759. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  49760. backend.state.unbindTexture();
  49761. // debug
  49762. // const framebuffer = gl.createFramebuffer();
  49763. // backend.state.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  49764. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  49765. // const readout = new Float32Array( width * height * 4 );
  49766. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  49767. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  49768. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  49769. // backend.state.bindFramebuffer( gl.FRAMEBUFFER, null );
  49770. // log( readout );
  49771. }
  49772. /**
  49773. * Uploads the updated texture data to the GPU.
  49774. *
  49775. * @param {Texture} texture - The texture.
  49776. * @param {Object} [options={}] - Optional configuration parameter.
  49777. */
  49778. updateTexture( texture, options ) {
  49779. const { gl } = this;
  49780. const { width, height } = options;
  49781. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  49782. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  49783. return;
  49784. this.backend.state.bindTexture( glTextureType, textureGPU );
  49785. this.setTextureParameters( glTextureType, texture );
  49786. if ( texture.isCompressedTexture ) {
  49787. const mipmaps = texture.mipmaps;
  49788. const image = options.image;
  49789. for ( let i = 0; i < mipmaps.length; i ++ ) {
  49790. const mipmap = mipmaps[ i ];
  49791. if ( texture.isCompressedArrayTexture ) {
  49792. if ( texture.format !== gl.RGBA ) {
  49793. if ( glFormat !== null ) {
  49794. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  49795. } else {
  49796. warn( 'WebGLBackend: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  49797. }
  49798. } else {
  49799. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  49800. }
  49801. } else {
  49802. if ( glFormat !== null ) {
  49803. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  49804. } else {
  49805. warn( 'WebGLBackend: Unsupported compressed texture format' );
  49806. }
  49807. }
  49808. }
  49809. } else if ( texture.isCubeTexture ) {
  49810. const images = options.images;
  49811. const mipmaps = texture.mipmaps;
  49812. for ( let i = 0; i < 6; i ++ ) {
  49813. const image = getImage( images[ i ] );
  49814. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  49815. for ( let j = 0; j < mipmaps.length; j ++ ) {
  49816. const mipmap = mipmaps[ j ];
  49817. const image = getImage( mipmap.images[ i ] );
  49818. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, image.width, image.height, glFormat, glType, image );
  49819. }
  49820. }
  49821. } else if ( texture.isDataArrayTexture || texture.isArrayTexture ) {
  49822. const image = options.image;
  49823. if ( texture.layerUpdates.size > 0 ) {
  49824. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  49825. for ( const layerIndex of texture.layerUpdates ) {
  49826. const layerData = image.data.subarray(
  49827. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  49828. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  49829. );
  49830. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  49831. }
  49832. texture.clearLayerUpdates();
  49833. } else {
  49834. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  49835. }
  49836. } else if ( texture.isData3DTexture ) {
  49837. const image = options.image;
  49838. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  49839. } else if ( texture.isVideoTexture ) {
  49840. texture.update();
  49841. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  49842. } else if ( texture.isHTMLTexture ) {
  49843. if ( typeof gl.texElementImage2D === 'function' ) {
  49844. if ( gl.texElementImage2D.length === 3 ) {
  49845. // Chrome 150+
  49846. gl.texElementImage2D( gl.TEXTURE_2D, gl.RGBA8, options.image );
  49847. } else {
  49848. // Chrome 138 - 149
  49849. gl.texElementImage2D( gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, options.image );
  49850. }
  49851. }
  49852. } else {
  49853. const mipmaps = texture.mipmaps;
  49854. if ( mipmaps.length > 0 ) {
  49855. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  49856. const mipmap = mipmaps[ i ];
  49857. const image = getImage( mipmap );
  49858. gl.texSubImage2D( glTextureType, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, image );
  49859. }
  49860. } else {
  49861. const image = getImage( options.image );
  49862. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  49863. }
  49864. }
  49865. }
  49866. /**
  49867. * Generates mipmaps for the given texture.
  49868. *
  49869. * @param {Texture} texture - The texture.
  49870. */
  49871. generateMipmaps( texture ) {
  49872. const { gl, backend } = this;
  49873. const { textureGPU, glTextureType } = backend.get( texture );
  49874. backend.state.bindTexture( glTextureType, textureGPU );
  49875. gl.generateMipmap( glTextureType );
  49876. }
  49877. /**
  49878. * Deallocates the render buffers of the given render target.
  49879. *
  49880. * @param {RenderTarget} renderTarget - The render target.
  49881. */
  49882. deallocateRenderBuffers( renderTarget ) {
  49883. const { gl, backend } = this;
  49884. // remove framebuffer reference
  49885. if ( renderTarget ) {
  49886. const renderContextData = backend.get( renderTarget );
  49887. renderContextData.renderBufferStorageSetup = undefined;
  49888. if ( renderContextData.framebuffers ) {
  49889. for ( const cacheKey in renderContextData.framebuffers ) {
  49890. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  49891. }
  49892. delete renderContextData.framebuffers;
  49893. }
  49894. if ( renderContextData.depthRenderbuffer ) {
  49895. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  49896. delete renderContextData.depthRenderbuffer;
  49897. }
  49898. if ( renderContextData.stencilRenderbuffer ) {
  49899. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  49900. delete renderContextData.stencilRenderbuffer;
  49901. }
  49902. if ( renderContextData.msaaFrameBuffer ) {
  49903. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  49904. delete renderContextData.msaaFrameBuffer;
  49905. }
  49906. if ( renderContextData.msaaRenderbuffers ) {
  49907. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  49908. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  49909. }
  49910. delete renderContextData.msaaRenderbuffers;
  49911. }
  49912. }
  49913. }
  49914. /**
  49915. * Destroys the GPU data for the given texture object.
  49916. *
  49917. * @param {Texture} texture - The texture.
  49918. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  49919. */
  49920. destroyTexture( texture, isDefaultTexture = false ) {
  49921. const { gl, backend } = this;
  49922. const { textureGPU, renderTarget } = backend.get( texture );
  49923. this.deallocateRenderBuffers( renderTarget );
  49924. if ( isDefaultTexture === false && texture.isExternalTexture !== true ) {
  49925. gl.deleteTexture( textureGPU );
  49926. }
  49927. backend.delete( texture );
  49928. }
  49929. /**
  49930. * Copies data of the given source texture to the given destination texture.
  49931. *
  49932. * @param {Texture} srcTexture - The source texture.
  49933. * @param {Texture} dstTexture - The destination texture.
  49934. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  49935. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  49936. * @param {number} [srcLevel=0] - The source mip level to copy from.
  49937. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  49938. */
  49939. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  49940. const { gl, backend } = this;
  49941. const { state } = this.backend;
  49942. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  49943. state.bindTexture( glTextureType, dstTextureGPU );
  49944. // gather the necessary dimensions to copy
  49945. let width, height, depth, minX, minY, minZ;
  49946. let dstX, dstY, dstZ;
  49947. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  49948. if ( srcRegion !== null ) {
  49949. width = srcRegion.max.x - srcRegion.min.x;
  49950. height = srcRegion.max.y - srcRegion.min.y;
  49951. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  49952. minX = srcRegion.min.x;
  49953. minY = srcRegion.min.y;
  49954. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  49955. } else {
  49956. const levelScale = Math.pow( 2, - srcLevel );
  49957. width = Math.floor( image.width * levelScale );
  49958. height = Math.floor( image.height * levelScale );
  49959. if ( srcTexture.isDataArrayTexture || srcTexture.isArrayTexture ) {
  49960. depth = image.depth;
  49961. } else if ( srcTexture.isData3DTexture ) {
  49962. depth = Math.floor( image.depth * levelScale );
  49963. } else {
  49964. depth = 1;
  49965. }
  49966. minX = 0;
  49967. minY = 0;
  49968. minZ = 0;
  49969. }
  49970. if ( dstPosition !== null ) {
  49971. dstX = dstPosition.x;
  49972. dstY = dstPosition.y;
  49973. dstZ = dstPosition.z;
  49974. } else {
  49975. dstX = 0;
  49976. dstY = 0;
  49977. dstZ = 0;
  49978. }
  49979. state.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  49980. state.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  49981. state.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  49982. // used for copying data from cpu
  49983. const currentUnpackRowLen = state.getParameter( gl.UNPACK_ROW_LENGTH );
  49984. const currentUnpackImageHeight = state.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  49985. const currentUnpackSkipPixels = state.getParameter( gl.UNPACK_SKIP_PIXELS );
  49986. const currentUnpackSkipRows = state.getParameter( gl.UNPACK_SKIP_ROWS );
  49987. const currentUnpackSkipImages = state.getParameter( gl.UNPACK_SKIP_IMAGES );
  49988. state.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  49989. state.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  49990. state.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  49991. state.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  49992. state.pixelStorei( gl.UNPACK_SKIP_IMAGES, minZ );
  49993. // set up the src texture
  49994. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture || dstTexture.isArrayTexture;
  49995. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture || dstTexture.isArrayTexture;
  49996. if ( srcTexture.isDepthTexture ) {
  49997. const srcTextureData = backend.get( srcTexture );
  49998. const dstTextureData = backend.get( dstTexture );
  49999. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  50000. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  50001. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  50002. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  50003. const prevReadFramebuffer = state.currentBoundFramebuffers[ gl.READ_FRAMEBUFFER ] ?? null;
  50004. const prevDrawFramebuffer = state.currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] ?? null;
  50005. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  50006. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  50007. for ( let i = 0; i < depth; i ++ ) {
  50008. // if the source or destination are a 3d target then a layer needs to be bound
  50009. if ( isSrc3D ) {
  50010. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  50011. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  50012. }
  50013. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.DEPTH_BUFFER_BIT, gl.NEAREST );
  50014. }
  50015. state.bindFramebuffer( gl.READ_FRAMEBUFFER, prevReadFramebuffer );
  50016. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, prevDrawFramebuffer );
  50017. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || backend.has( srcTexture ) ) {
  50018. // get the appropriate frame buffers
  50019. const srcTextureData = backend.get( srcTexture );
  50020. if ( this._srcFramebuffer === null ) this._srcFramebuffer = gl.createFramebuffer();
  50021. if ( this._dstFramebuffer === null ) this._dstFramebuffer = gl.createFramebuffer();
  50022. const prevReadFramebuffer = state.currentBoundFramebuffers[ gl.READ_FRAMEBUFFER ] ?? null;
  50023. const prevDrawFramebuffer = state.currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] ?? null;
  50024. // bind the frame buffer targets
  50025. state.bindFramebuffer( gl.READ_FRAMEBUFFER, this._srcFramebuffer );
  50026. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, this._dstFramebuffer );
  50027. for ( let i = 0; i < depth; i ++ ) {
  50028. // assign the correct layers and mip maps to the frame buffers
  50029. if ( isSrc3D ) {
  50030. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  50031. } else {
  50032. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, srcTextureData.textureGPU, srcLevel );
  50033. }
  50034. if ( isDst3D ) {
  50035. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  50036. } else {
  50037. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, dstTextureGPU, dstLevel );
  50038. }
  50039. // copy the data using the fastest function that can achieve the copy
  50040. if ( srcLevel !== 0 ) {
  50041. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.COLOR_BUFFER_BIT, gl.NEAREST );
  50042. } else if ( isDst3D ) {
  50043. gl.copyTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  50044. } else {
  50045. gl.copyTexSubImage2D( glTextureType, dstLevel, dstX, dstY, minX, minY, width, height );
  50046. }
  50047. }
  50048. // restore previous read, draw framebuffer bindings
  50049. state.bindFramebuffer( gl.READ_FRAMEBUFFER, prevReadFramebuffer );
  50050. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, prevDrawFramebuffer );
  50051. } else {
  50052. if ( isDst3D ) {
  50053. // copy data into the 3d texture
  50054. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  50055. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  50056. } else if ( dstTexture.isCompressedArrayTexture ) {
  50057. gl.compressedTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  50058. } else {
  50059. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  50060. }
  50061. } else {
  50062. // copy data into the 2d texture
  50063. if ( srcTexture.isDataTexture ) {
  50064. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  50065. } else if ( srcTexture.isCompressedTexture ) {
  50066. gl.compressedTexSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  50067. } else {
  50068. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  50069. }
  50070. }
  50071. }
  50072. // reset values
  50073. state.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  50074. state.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  50075. state.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  50076. state.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  50077. state.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  50078. // Generate mipmaps only when copying level 0
  50079. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  50080. gl.generateMipmap( glTextureType );
  50081. }
  50082. state.unbindTexture();
  50083. }
  50084. /**
  50085. * Copies the current bound framebuffer to the given texture.
  50086. *
  50087. * @param {Texture} texture - The destination texture.
  50088. * @param {RenderContext} renderContext - The render context.
  50089. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  50090. */
  50091. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  50092. const { gl } = this;
  50093. const { state } = this.backend;
  50094. const { textureGPU } = this.backend.get( texture );
  50095. const { x, y, z: width, w: height } = rectangle;
  50096. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  50097. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  50098. if ( requireDrawFrameBuffer ) {
  50099. const partial = ( x !== 0 || y !== 0 );
  50100. let mask;
  50101. let attachment;
  50102. if ( texture.isDepthTexture === true ) {
  50103. mask = gl.DEPTH_BUFFER_BIT;
  50104. attachment = gl.DEPTH_ATTACHMENT;
  50105. if ( renderContext.stencil ) {
  50106. mask |= gl.STENCIL_BUFFER_BIT;
  50107. }
  50108. } else {
  50109. mask = gl.COLOR_BUFFER_BIT;
  50110. attachment = gl.COLOR_ATTACHMENT0;
  50111. }
  50112. if ( partial ) {
  50113. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  50114. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  50115. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  50116. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  50117. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  50118. const flippedY = srcHeight - y - height;
  50119. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  50120. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  50121. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  50122. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  50123. state.unbindTexture();
  50124. } else {
  50125. const fb = gl.createFramebuffer();
  50126. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  50127. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  50128. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  50129. gl.deleteFramebuffer( fb );
  50130. }
  50131. } else {
  50132. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  50133. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  50134. state.unbindTexture();
  50135. }
  50136. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  50137. this.backend._setFramebuffer( renderContext );
  50138. }
  50139. /**
  50140. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  50141. *
  50142. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  50143. * @param {RenderContext} renderContext - The render context.
  50144. * @param {number} samples - The MSAA sample count.
  50145. * @param {boolean} [useMultisampledRTT=false] - Whether to use WEBGL_multisampled_render_to_texture or not.
  50146. */
  50147. setupRenderBufferStorage( renderbuffer, renderContext, samples, useMultisampledRTT = false ) {
  50148. const { gl } = this;
  50149. const renderTarget = renderContext.renderTarget;
  50150. const { depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  50151. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  50152. if ( depthBuffer && ! stencilBuffer ) {
  50153. let glInternalFormat = gl.DEPTH_COMPONENT24;
  50154. if ( useMultisampledRTT === true ) {
  50155. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  50156. multisampledRTTExt.renderbufferStorageMultisampleEXT( gl.RENDERBUFFER, renderTarget.samples, glInternalFormat, width, height );
  50157. } else if ( samples > 0 ) {
  50158. if ( depthTexture && depthTexture.isDepthTexture ) {
  50159. if ( depthTexture.type === gl.FLOAT ) {
  50160. glInternalFormat = gl.DEPTH_COMPONENT32F;
  50161. }
  50162. }
  50163. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  50164. } else {
  50165. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  50166. }
  50167. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  50168. } else if ( depthBuffer && stencilBuffer ) {
  50169. if ( samples > 0 ) {
  50170. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  50171. } else {
  50172. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  50173. }
  50174. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  50175. }
  50176. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  50177. }
  50178. /**
  50179. * Returns texture data as a typed array.
  50180. *
  50181. * @async
  50182. * @param {Texture} texture - The texture to copy.
  50183. * @param {number} x - The x coordinate of the copy origin.
  50184. * @param {number} y - The y coordinate of the copy origin.
  50185. * @param {number} width - The width of the copy.
  50186. * @param {number} height - The height of the copy.
  50187. * @param {number} faceIndex - The face index.
  50188. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  50189. */
  50190. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  50191. const { backend, gl } = this;
  50192. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  50193. const fb = gl.createFramebuffer();
  50194. backend.state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  50195. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  50196. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  50197. const typedArrayType = this._getTypedArrayType( glType );
  50198. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  50199. const elementCount = width * height;
  50200. const byteLength = elementCount * bytesPerTexel;
  50201. const buffer = gl.createBuffer();
  50202. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  50203. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  50204. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  50205. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  50206. await backend.utils._clientWaitAsync();
  50207. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  50208. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  50209. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  50210. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  50211. backend.state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  50212. gl.deleteFramebuffer( fb );
  50213. return dstBuffer;
  50214. }
  50215. /**
  50216. * Returns the corresponding typed array type for the given WebGL data type.
  50217. *
  50218. * @private
  50219. * @param {GLenum} glType - The WebGL data type.
  50220. * @return {TypedArray.constructor} The typed array type.
  50221. */
  50222. _getTypedArrayType( glType ) {
  50223. const { gl } = this;
  50224. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  50225. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  50226. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  50227. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  50228. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  50229. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  50230. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  50231. if ( glType === gl.FLOAT ) return Float32Array;
  50232. throw new Error( `THREE.WebGLTextureUtils: Unsupported WebGL type: ${glType}` );
  50233. }
  50234. /**
  50235. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  50236. *
  50237. * @private
  50238. * @param {GLenum} glType - The WebGL data type.
  50239. * @param {GLenum} glFormat - The WebGL texture format.
  50240. * @return {number} The bytes-per-texel.
  50241. */
  50242. _getBytesPerTexel( glType, glFormat ) {
  50243. const { gl } = this;
  50244. let bytesPerComponent = 0;
  50245. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  50246. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  50247. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  50248. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  50249. glType === gl.UNSIGNED_SHORT ||
  50250. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  50251. if ( glType === gl.UNSIGNED_INT ||
  50252. glType === gl.FLOAT ) bytesPerComponent = 4;
  50253. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  50254. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  50255. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  50256. }
  50257. /**
  50258. * Frees the internal resources.
  50259. */
  50260. dispose() {
  50261. const { gl } = this;
  50262. if ( this._srcFramebuffer !== null ) gl.deleteFramebuffer( this._srcFramebuffer );
  50263. if ( this._dstFramebuffer !== null ) gl.deleteFramebuffer( this._dstFramebuffer );
  50264. }
  50265. }
  50266. function getImage( source ) {
  50267. if ( source.isDataTexture ) {
  50268. return source.image.data;
  50269. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  50270. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  50271. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  50272. ( typeof OffscreenCanvas !== 'undefined' && source instanceof OffscreenCanvas ) ) {
  50273. return source;
  50274. }
  50275. return source.data;
  50276. }
  50277. /**
  50278. * A WebGL 2 backend utility module for managing extensions.
  50279. *
  50280. * @private
  50281. */
  50282. class WebGLExtensions {
  50283. /**
  50284. * Constructs a new utility object.
  50285. *
  50286. * @param {WebGLBackend} backend - The WebGL 2 backend.
  50287. */
  50288. constructor( backend ) {
  50289. /**
  50290. * A reference to the WebGL 2 backend.
  50291. *
  50292. * @type {WebGLBackend}
  50293. */
  50294. this.backend = backend;
  50295. /**
  50296. * A reference to the rendering context.
  50297. *
  50298. * @type {WebGL2RenderingContext}
  50299. */
  50300. this.gl = this.backend.gl;
  50301. /**
  50302. * A list with all the supported WebGL extensions.
  50303. *
  50304. * @type {Array<string>}
  50305. */
  50306. this.availableExtensions = this.gl.getSupportedExtensions();
  50307. /**
  50308. * A dictionary with requested WebGL extensions.
  50309. * The key is the name of the extension, the value
  50310. * the requested extension object.
  50311. *
  50312. * @type {Object<string,Object>}
  50313. */
  50314. this.extensions = {};
  50315. }
  50316. /**
  50317. * Returns the extension object for the given extension name.
  50318. *
  50319. * @param {string} name - The extension name.
  50320. * @return {Object} The extension object.
  50321. */
  50322. get( name ) {
  50323. let extension = this.extensions[ name ];
  50324. if ( extension === undefined ) {
  50325. extension = this.gl.getExtension( name );
  50326. this.extensions[ name ] = extension;
  50327. }
  50328. return extension;
  50329. }
  50330. /**
  50331. * Returns `true` if the requested extension is available.
  50332. *
  50333. * @param {string} name - The extension name.
  50334. * @return {boolean} Whether the given extension is available or not.
  50335. */
  50336. has( name ) {
  50337. return this.availableExtensions.includes( name );
  50338. }
  50339. }
  50340. /**
  50341. * A WebGL 2 backend utility module for managing the device's capabilities.
  50342. *
  50343. * @private
  50344. */
  50345. class WebGLCapabilities {
  50346. /**
  50347. * Constructs a new utility object.
  50348. *
  50349. * @param {WebGLBackend} backend - The WebGL 2 backend.
  50350. */
  50351. constructor( backend ) {
  50352. /**
  50353. * A reference to the WebGL 2 backend.
  50354. *
  50355. * @type {WebGLBackend}
  50356. */
  50357. this.backend = backend;
  50358. /**
  50359. * This value holds the cached max anisotropy value.
  50360. *
  50361. * @type {?number}
  50362. * @default null
  50363. */
  50364. this.maxAnisotropy = null;
  50365. /**
  50366. * This value holds the cached max uniform block size value.
  50367. *
  50368. * @type {?number}
  50369. * @default null
  50370. */
  50371. this.maxUniformBlockSize = null;
  50372. }
  50373. /**
  50374. * Returns the maximum anisotropy texture filtering value. This value
  50375. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  50376. * WebGL extension.
  50377. *
  50378. * @return {number} The maximum anisotropy texture filtering value.
  50379. */
  50380. getMaxAnisotropy() {
  50381. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  50382. const gl = this.backend.gl;
  50383. const extensions = this.backend.extensions;
  50384. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  50385. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  50386. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  50387. } else {
  50388. this.maxAnisotropy = 0;
  50389. }
  50390. return this.maxAnisotropy;
  50391. }
  50392. /**
  50393. * Returns the maximum number of bytes available for uniform buffers.
  50394. *
  50395. * @return {number} The maximum number of bytes available for uniform buffers.
  50396. */
  50397. getUniformBufferLimit() {
  50398. if ( this.maxUniformBlockSize !== null ) return this.maxUniformBlockSize;
  50399. const gl = this.backend.gl;
  50400. this.maxUniformBlockSize = gl.getParameter( gl.MAX_UNIFORM_BLOCK_SIZE );
  50401. return this.maxUniformBlockSize;
  50402. }
  50403. }
  50404. const GLFeatureName = {
  50405. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  50406. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  50407. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  50408. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  50409. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  50410. 'WEBGL_compressed_texture_s3tc': 'texture-compression-s3tc',
  50411. 'EXT_texture_compression_bptc': 'texture-compression-bc',
  50412. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  50413. 'OVR_multiview2': 'OVR_multiview2'
  50414. };
  50415. class WebGLBufferRenderer {
  50416. constructor( backend ) {
  50417. this.gl = backend.gl;
  50418. this.extensions = backend.extensions;
  50419. this.info = backend.renderer.info;
  50420. this.mode = null;
  50421. this.index = 0;
  50422. this.type = null;
  50423. this.object = null;
  50424. }
  50425. render( start, count ) {
  50426. const { gl, mode, object, type, info, index } = this;
  50427. if ( index !== 0 ) {
  50428. gl.drawElements( mode, count, type, start );
  50429. } else {
  50430. gl.drawArrays( mode, start, count );
  50431. }
  50432. info.update( object, count, 1 );
  50433. }
  50434. renderInstances( start, count, primcount ) {
  50435. const { gl, mode, type, index, object, info } = this;
  50436. if ( primcount === 0 ) return;
  50437. if ( index !== 0 ) {
  50438. gl.drawElementsInstanced( mode, count, type, start, primcount );
  50439. } else {
  50440. gl.drawArraysInstanced( mode, start, count, primcount );
  50441. }
  50442. info.update( object, count, primcount );
  50443. }
  50444. renderMultiDraw( starts, counts, drawCount ) {
  50445. const { extensions, mode, object, info } = this;
  50446. if ( drawCount === 0 ) return;
  50447. const extension = extensions.get( 'WEBGL_multi_draw' );
  50448. if ( extension === null ) {
  50449. for ( let i = 0; i < drawCount; i ++ ) {
  50450. this.render( starts[ i ], counts[ i ] );
  50451. }
  50452. } else {
  50453. if ( this.index !== 0 ) {
  50454. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  50455. } else {
  50456. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  50457. }
  50458. let elementCount = 0;
  50459. for ( let i = 0; i < drawCount; i ++ ) {
  50460. elementCount += counts[ i ];
  50461. }
  50462. info.update( object, elementCount, 1 );
  50463. }
  50464. }
  50465. //
  50466. }
  50467. /**
  50468. * Abstract base class of a timestamp query pool.
  50469. *
  50470. * @abstract
  50471. */
  50472. class TimestampQueryPool {
  50473. /**
  50474. * Creates a new timestamp query pool.
  50475. *
  50476. * @param {number} [maxQueries=256] - Maximum number of queries this pool can hold.
  50477. */
  50478. constructor( maxQueries = 256 ) {
  50479. /**
  50480. * Whether to track timestamps or not.
  50481. *
  50482. * @type {boolean}
  50483. * @default true
  50484. */
  50485. this.trackTimestamp = true;
  50486. /**
  50487. * Maximum number of queries this pool can hold.
  50488. *
  50489. * @type {number}
  50490. * @default 256
  50491. */
  50492. this.maxQueries = maxQueries;
  50493. /**
  50494. * How many queries allocated so far.
  50495. *
  50496. * @type {number}
  50497. * @default 0
  50498. */
  50499. this.currentQueryIndex = 0;
  50500. /**
  50501. * Tracks offsets for different contexts.
  50502. *
  50503. * @type {Map<string, number>}
  50504. */
  50505. this.queryOffsets = new Map();
  50506. /**
  50507. * Whether the pool has been disposed or not.
  50508. *
  50509. * @type {boolean}
  50510. * @default false
  50511. */
  50512. this.isDisposed = false;
  50513. /**
  50514. * The total frame duration until the next update.
  50515. *
  50516. * @type {number}
  50517. * @default 0
  50518. */
  50519. this.lastValue = 0;
  50520. /**
  50521. * Stores all timestamp frames.
  50522. *
  50523. * @type {Array<number>}
  50524. */
  50525. this.frames = [];
  50526. /**
  50527. * This property is used to avoid multiple concurrent resolve operations.
  50528. * The WebGL backend uses it as a boolean flag. In context of WebGPU, it holds
  50529. * the promise of the current resolve operation.
  50530. *
  50531. * @type {boolean|Promise<number>}
  50532. * @default false
  50533. */
  50534. this.pendingResolve = false;
  50535. /**
  50536. * Stores the latest timestamp for each render context.
  50537. *
  50538. * @type {Map<string, number>}
  50539. */
  50540. this.timestamps = new Map();
  50541. }
  50542. /**
  50543. * Returns all timestamp frames.
  50544. *
  50545. * @return {Array<number>} The timestamp frames.
  50546. */
  50547. getTimestampFrames() {
  50548. return this.frames;
  50549. }
  50550. /**
  50551. * Returns the timestamp for a given render context.
  50552. *
  50553. * @param {string} uid - A unique identifier for the render context.
  50554. * @return {?number} The timestamp, or undefined if not available.
  50555. */
  50556. getTimestamp( uid ) {
  50557. let timestamp = this.timestamps.get( uid );
  50558. if ( timestamp === undefined ) {
  50559. warn( `TimestampQueryPool: No timestamp available for uid ${ uid }.` );
  50560. timestamp = 0;
  50561. }
  50562. return timestamp;
  50563. }
  50564. /**
  50565. * Returns whether a timestamp is available for a given render context.
  50566. *
  50567. * @param {string} uid - A unique identifier for the render context.
  50568. * @return {boolean} True if a timestamp is available, false otherwise.
  50569. */
  50570. hasTimestampQuery( uid ) {
  50571. return this.timestamps.has( uid );
  50572. }
  50573. /**
  50574. * Allocate queries for a specific uid.
  50575. *
  50576. * @abstract
  50577. * @param {string} uid - A unique identifier for the render context.
  50578. * @param {number} frameId - The current frame identifier.
  50579. * @returns {?number}
  50580. */
  50581. allocateQueriesForContext( /* uid, frameId */ ) {}
  50582. /**
  50583. * Resolve all timestamps and return data (or process them).
  50584. *
  50585. * @abstract
  50586. * @async
  50587. * @returns {Promise<number>|number} The resolved timestamp value.
  50588. */
  50589. async resolveQueriesAsync() {}
  50590. /**
  50591. * Dispose of the query pool.
  50592. *
  50593. * @abstract
  50594. */
  50595. dispose() {}
  50596. }
  50597. /**
  50598. * Manages a pool of WebGL timestamp queries for performance measurement.
  50599. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  50600. *
  50601. * @augments TimestampQueryPool
  50602. */
  50603. class WebGLTimestampQueryPool extends TimestampQueryPool {
  50604. /**
  50605. * Creates a new WebGL timestamp query pool.
  50606. *
  50607. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  50608. * @param {string} type - The type identifier for this query pool.
  50609. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  50610. */
  50611. constructor( gl, type, maxQueries = 2048 ) {
  50612. super( maxQueries );
  50613. this.gl = gl;
  50614. this.type = type;
  50615. // Check for timer query extensions
  50616. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  50617. gl.getExtension( 'EXT_disjoint_timer_query' );
  50618. if ( ! this.ext ) {
  50619. warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  50620. this.trackTimestamp = false;
  50621. return;
  50622. }
  50623. // Create query objects
  50624. this.queries = [];
  50625. for ( let i = 0; i < this.maxQueries; i ++ ) {
  50626. this.queries.push( gl.createQuery() );
  50627. }
  50628. this.activeQuery = null;
  50629. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  50630. }
  50631. /**
  50632. * Allocates a pair of queries for a given render context.
  50633. *
  50634. * @param {string} uid - A unique identifier for the render context.
  50635. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  50636. */
  50637. allocateQueriesForContext( uid ) {
  50638. if ( ! this.trackTimestamp ) return null;
  50639. // Check if we have enough space for a new query pair
  50640. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  50641. warnOnce( `WebGLTimestampQueryPool [${ this.type }]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${ this.type.toUpperCase() } ).` );
  50642. return null;
  50643. }
  50644. const baseOffset = this.currentQueryIndex;
  50645. this.currentQueryIndex += 2;
  50646. // Initialize query states
  50647. this.queryStates.set( baseOffset, 'inactive' );
  50648. this.queryOffsets.set( uid, baseOffset );
  50649. return baseOffset;
  50650. }
  50651. /**
  50652. * Begins a timestamp query for the specified render context.
  50653. *
  50654. * @param {string} uid - A unique identifier for the render context.
  50655. */
  50656. beginQuery( uid ) {
  50657. if ( ! this.trackTimestamp || this.isDisposed ) {
  50658. return;
  50659. }
  50660. const baseOffset = this.queryOffsets.get( uid );
  50661. if ( baseOffset == null ) {
  50662. return;
  50663. }
  50664. // Don't start a new query if there's an active one
  50665. if ( this.activeQuery !== null ) {
  50666. return;
  50667. }
  50668. const query = this.queries[ baseOffset ];
  50669. if ( ! query ) {
  50670. return;
  50671. }
  50672. try {
  50673. // Only begin if query is inactive
  50674. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  50675. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  50676. this.activeQuery = baseOffset;
  50677. this.queryStates.set( baseOffset, 'started' );
  50678. }
  50679. } catch ( e ) {
  50680. error( 'Error in beginQuery:', e );
  50681. this.activeQuery = null;
  50682. this.queryStates.set( baseOffset, 'inactive' );
  50683. }
  50684. }
  50685. /**
  50686. * Ends the active timestamp query for the specified render context.
  50687. *
  50688. * @param {string} uid - A unique identifier for the render context.
  50689. */
  50690. endQuery( uid ) {
  50691. if ( ! this.trackTimestamp || this.isDisposed ) {
  50692. return;
  50693. }
  50694. const baseOffset = this.queryOffsets.get( uid );
  50695. if ( baseOffset == null ) {
  50696. return;
  50697. }
  50698. // Only end if this is the active query
  50699. if ( this.activeQuery !== baseOffset ) {
  50700. return;
  50701. }
  50702. try {
  50703. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  50704. this.queryStates.set( baseOffset, 'ended' );
  50705. this.activeQuery = null;
  50706. } catch ( e ) {
  50707. error( 'Error in endQuery:', e );
  50708. // Reset state on error
  50709. this.queryStates.set( baseOffset, 'inactive' );
  50710. this.activeQuery = null;
  50711. }
  50712. }
  50713. /**
  50714. * Asynchronously resolves all completed queries and returns the total duration.
  50715. *
  50716. * @async
  50717. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  50718. */
  50719. async resolveQueriesAsync() {
  50720. if ( ! this.trackTimestamp || this.pendingResolve ) {
  50721. return this.lastValue;
  50722. }
  50723. this.pendingResolve = true;
  50724. try {
  50725. // Wait for all ended queries to complete
  50726. const resolvePromises = new Map();
  50727. for ( const [ uid, baseOffset ] of this.queryOffsets ) {
  50728. const state = this.queryStates.get( baseOffset );
  50729. if ( state === 'ended' ) {
  50730. const query = this.queries[ baseOffset ];
  50731. resolvePromises.set( uid, this.resolveQuery( query ) );
  50732. }
  50733. }
  50734. if ( resolvePromises.size === 0 ) {
  50735. return this.lastValue;
  50736. }
  50737. //
  50738. const framesDuration = {};
  50739. const frames = [];
  50740. for ( const [ uid, promise ] of resolvePromises ) {
  50741. const match = uid.match( /^(.*):f(\d+)$/ );
  50742. const frame = parseInt( match[ 2 ] );
  50743. if ( frames.includes( frame ) === false ) {
  50744. frames.push( frame );
  50745. }
  50746. if ( framesDuration[ frame ] === undefined ) framesDuration[ frame ] = 0;
  50747. const duration = await promise;
  50748. this.timestamps.set( uid, duration );
  50749. framesDuration[ frame ] += duration;
  50750. }
  50751. // Return the total duration of the last frame
  50752. const totalDuration = framesDuration[ frames[ frames.length - 1 ] ];
  50753. // Store the last valid result
  50754. this.lastValue = totalDuration;
  50755. this.frames = frames;
  50756. // Reset states
  50757. this.currentQueryIndex = 0;
  50758. this.queryOffsets.clear();
  50759. this.queryStates.clear();
  50760. this.activeQuery = null;
  50761. return totalDuration;
  50762. } catch ( e ) {
  50763. error( 'Error resolving queries:', e );
  50764. return this.lastValue;
  50765. } finally {
  50766. this.pendingResolve = false;
  50767. }
  50768. }
  50769. /**
  50770. * Resolves a single query, checking for completion and disjoint operation.
  50771. *
  50772. * @async
  50773. * @param {WebGLQuery} query - The query object to resolve.
  50774. * @returns {Promise<number>} The elapsed time in milliseconds.
  50775. */
  50776. async resolveQuery( query ) {
  50777. return new Promise( ( resolve ) => {
  50778. if ( this.isDisposed ) {
  50779. resolve( this.lastValue );
  50780. return;
  50781. }
  50782. let timeoutId;
  50783. let isResolved = false;
  50784. const cleanup = () => {
  50785. if ( timeoutId ) {
  50786. clearTimeout( timeoutId );
  50787. timeoutId = null;
  50788. }
  50789. };
  50790. const finalizeResolution = ( value ) => {
  50791. if ( ! isResolved ) {
  50792. isResolved = true;
  50793. cleanup();
  50794. resolve( value );
  50795. }
  50796. };
  50797. const checkQuery = () => {
  50798. if ( this.isDisposed ) {
  50799. finalizeResolution( this.lastValue );
  50800. return;
  50801. }
  50802. try {
  50803. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  50804. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  50805. if ( disjoint ) {
  50806. finalizeResolution( this.lastValue );
  50807. return;
  50808. }
  50809. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  50810. if ( ! available ) {
  50811. timeoutId = setTimeout( checkQuery, 1 );
  50812. return;
  50813. }
  50814. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  50815. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  50816. } catch ( e ) {
  50817. error( 'Error checking query:', e );
  50818. resolve( this.lastValue );
  50819. }
  50820. };
  50821. checkQuery();
  50822. } );
  50823. }
  50824. /**
  50825. * Releases all resources held by this query pool.
  50826. * This includes deleting all query objects and clearing internal state.
  50827. */
  50828. dispose() {
  50829. if ( this.isDisposed ) {
  50830. return;
  50831. }
  50832. this.isDisposed = true;
  50833. if ( ! this.trackTimestamp ) return;
  50834. for ( const query of this.queries ) {
  50835. this.gl.deleteQuery( query );
  50836. }
  50837. this.queries = [];
  50838. this.queryStates.clear();
  50839. this.queryOffsets.clear();
  50840. this.lastValue = 0;
  50841. this.activeQuery = null;
  50842. }
  50843. }
  50844. const _invalidationArray = [];
  50845. /**
  50846. * A backend implementation targeting WebGL 2.
  50847. *
  50848. * @private
  50849. * @augments Backend
  50850. */
  50851. class WebGLBackend extends Backend {
  50852. /**
  50853. * WebGLBackend options.
  50854. *
  50855. * @typedef {Object} WebGLBackend~Options
  50856. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  50857. * @property {boolean} [reversedDepthBuffer=false] - Whether reversed depth buffer is enabled or not.
  50858. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  50859. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  50860. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  50861. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  50862. * @property {number} [samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0 to overwrite the default.
  50863. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  50864. * @property {WebGL2RenderingContext} [context=undefined] - A WebGL 2 rendering context.
  50865. */
  50866. /**
  50867. * Constructs a new WebGPU backend.
  50868. *
  50869. * @param {WebGLBackend~Options} [parameters] - The configuration parameter.
  50870. */
  50871. constructor( parameters = {} ) {
  50872. super( parameters );
  50873. /**
  50874. * This flag can be used for type testing.
  50875. *
  50876. * @type {boolean}
  50877. * @readonly
  50878. * @default true
  50879. */
  50880. this.isWebGLBackend = true;
  50881. /**
  50882. * A reference to a backend module holding shader attribute-related
  50883. * utility functions.
  50884. *
  50885. * @type {?WebGLAttributeUtils}
  50886. * @default null
  50887. */
  50888. this.attributeUtils = null;
  50889. /**
  50890. * A reference to a backend module holding extension-related
  50891. * utility functions.
  50892. *
  50893. * @type {?WebGLExtensions}
  50894. * @default null
  50895. */
  50896. this.extensions = null;
  50897. /**
  50898. * A reference to a backend module holding capability-related
  50899. * utility functions.
  50900. *
  50901. * @type {?WebGLCapabilities}
  50902. * @default null
  50903. */
  50904. this.capabilities = null;
  50905. /**
  50906. * A reference to a backend module holding texture-related
  50907. * utility functions.
  50908. *
  50909. * @type {?WebGLTextureUtils}
  50910. * @default null
  50911. */
  50912. this.textureUtils = null;
  50913. /**
  50914. * A reference to a backend module holding renderer-related
  50915. * utility functions.
  50916. *
  50917. * @type {?WebGLBufferRenderer}
  50918. * @default null
  50919. */
  50920. this.bufferRenderer = null;
  50921. /**
  50922. * A reference to the rendering context.
  50923. *
  50924. * @type {?WebGL2RenderingContext}
  50925. * @default null
  50926. */
  50927. this.gl = null;
  50928. /**
  50929. * A reference to a backend module holding state-related
  50930. * utility functions.
  50931. *
  50932. * @type {?WebGLState}
  50933. * @default null
  50934. */
  50935. this.state = null;
  50936. /**
  50937. * A reference to a backend module holding common
  50938. * utility functions.
  50939. *
  50940. * @type {?WebGLUtils}
  50941. * @default null
  50942. */
  50943. this.utils = null;
  50944. /**
  50945. * Dictionary for caching VAOs.
  50946. *
  50947. * @type {Object<string,WebGLVertexArrayObject>}
  50948. */
  50949. this.vaoCache = {};
  50950. /**
  50951. * Dictionary for caching transform feedback objects.
  50952. *
  50953. * @type {Object<string,WebGLTransformFeedback>}
  50954. */
  50955. this.transformFeedbackCache = {};
  50956. /**
  50957. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  50958. * Only relevant when using compute shaders.
  50959. *
  50960. * @type {boolean}
  50961. * @default false
  50962. */
  50963. this.discard = false;
  50964. /**
  50965. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  50966. * device does not support the extension.
  50967. *
  50968. * @type {?EXTDisjointTimerQueryWebGL2}
  50969. * @default null
  50970. */
  50971. this.disjoint = null;
  50972. /**
  50973. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  50974. * device does not support the extension.
  50975. *
  50976. * @type {?KHRParallelShaderCompile}
  50977. * @default null
  50978. */
  50979. this.parallel = null;
  50980. /**
  50981. * A reference to the current render context.
  50982. *
  50983. * @private
  50984. * @type {RenderContext}
  50985. * @default null
  50986. */
  50987. this._currentContext = null;
  50988. /**
  50989. * A unique collection of bindings.
  50990. *
  50991. * @private
  50992. * @type {WeakSet<Array<BindGroup>>}
  50993. */
  50994. this._knownBindings = new WeakSet();
  50995. /**
  50996. * Whether the device supports framebuffers invalidation or not.
  50997. *
  50998. * @private
  50999. * @type {boolean}
  51000. */
  51001. this._supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  51002. /**
  51003. * The target framebuffer when rendering with
  51004. * the WebXR device API.
  51005. *
  51006. * @private
  51007. * @type {?WebGLFramebuffer}
  51008. * @default null
  51009. */
  51010. this._xrFramebuffer = null;
  51011. }
  51012. /**
  51013. * Initializes the backend so it is ready for usage.
  51014. *
  51015. * @param {Renderer} renderer - The renderer.
  51016. */
  51017. init( renderer ) {
  51018. super.init( renderer );
  51019. //
  51020. const parameters = this.parameters;
  51021. const contextAttributes = {
  51022. antialias: renderer.currentSamples > 0,
  51023. alpha: true, // always true for performance reasons
  51024. depth: renderer.depth,
  51025. stencil: renderer.stencil
  51026. };
  51027. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2', contextAttributes );
  51028. function onContextLost( event ) {
  51029. event.preventDefault();
  51030. const contextLossInfo = {
  51031. api: 'WebGL',
  51032. message: event.statusMessage || 'Unknown reason',
  51033. reason: null,
  51034. originalEvent: event
  51035. };
  51036. renderer.onDeviceLost( contextLossInfo );
  51037. }
  51038. this._onContextLost = onContextLost;
  51039. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  51040. this.gl = glContext;
  51041. this.extensions = new WebGLExtensions( this );
  51042. this.capabilities = new WebGLCapabilities( this );
  51043. this.attributeUtils = new WebGLAttributeUtils( this );
  51044. this.textureUtils = new WebGLTextureUtils( this );
  51045. this.bufferRenderer = new WebGLBufferRenderer( this );
  51046. this.state = new WebGLState( this );
  51047. this.utils = new WebGLUtils( this );
  51048. this.extensions.get( 'EXT_color_buffer_float' );
  51049. this.extensions.get( 'WEBGL_clip_cull_distance' );
  51050. this.extensions.get( 'OES_texture_float_linear' );
  51051. this.extensions.get( 'EXT_color_buffer_half_float' );
  51052. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  51053. this.extensions.get( 'WEBGL_render_shared_exponent' );
  51054. this.extensions.get( 'WEBGL_multi_draw' );
  51055. this.extensions.get( 'OVR_multiview2' );
  51056. this.extensions.get( 'EXT_clip_control' );
  51057. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  51058. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  51059. this.drawBuffersIndexedExt = this.extensions.get( 'OES_draw_buffers_indexed' );
  51060. if ( parameters.reversedDepthBuffer ) {
  51061. if ( this.extensions.has( 'EXT_clip_control' ) ) {
  51062. renderer.reversedDepthBuffer = true;
  51063. } else {
  51064. warn( 'WebGPURenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer.' );
  51065. renderer.reversedDepthBuffer = false;
  51066. }
  51067. }
  51068. if ( renderer.reversedDepthBuffer ) {
  51069. this.state.setReversedDepth( true );
  51070. }
  51071. }
  51072. /**
  51073. * The coordinate system of the backend.
  51074. *
  51075. * @type {number}
  51076. * @readonly
  51077. */
  51078. get coordinateSystem() {
  51079. return WebGLCoordinateSystem;
  51080. }
  51081. /**
  51082. * Whether the backend supports query timestamps or not.
  51083. *
  51084. * @type {boolean}
  51085. * @readonly
  51086. */
  51087. get hasTimestamp() {
  51088. return this.disjoint !== null;
  51089. }
  51090. /**
  51091. * This method performs a readback operation by moving buffer data from
  51092. * a storage buffer attribute from the GPU to the CPU. ReadbackBuffer can
  51093. * be used to retain and reuse handles to the intermediate buffers and prevent
  51094. * new allocation.
  51095. *
  51096. * @async
  51097. * @param {BufferAttribute} attribute - The storage buffer attribute to read frm.
  51098. * @param {ReadbackBuffer|ArrayBuffer} target - The storage buffer attribute.
  51099. * @param {number} offset - The storage buffer attribute.
  51100. * @param {number} count - The offset from which to start reading the
  51101. * @return {Promise<ArrayBuffer|ReadbackBuffer>} A promise that resolves with the buffer data when the data are ready.
  51102. */
  51103. async getArrayBufferAsync( attribute, target = null, offset = 0, count = -1 ) {
  51104. return await this.attributeUtils.getArrayBufferAsync( attribute, target, offset, count );
  51105. }
  51106. /**
  51107. * Ensures the backend is XR compatible.
  51108. *
  51109. * @async
  51110. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  51111. */
  51112. async makeXRCompatible() {
  51113. const attributes = this.gl.getContextAttributes();
  51114. if ( attributes.xrCompatible !== true ) {
  51115. await this.gl.makeXRCompatible();
  51116. }
  51117. }
  51118. /**
  51119. * Sets the XR rendering destination.
  51120. *
  51121. * @param {WebGLFramebuffer} xrFramebuffer - The XR framebuffer.
  51122. */
  51123. setXRTarget( xrFramebuffer ) {
  51124. this._xrFramebuffer = xrFramebuffer;
  51125. }
  51126. /**
  51127. * Configures the given XR render target with external textures.
  51128. *
  51129. * This method is only relevant when using the WebXR Layers API.
  51130. *
  51131. * @param {XRRenderTarget} renderTarget - The XR render target.
  51132. * @param {WebGLTexture} colorTexture - A native color texture.
  51133. * @param {?WebGLTexture} [depthTexture=null] - A native depth texture.
  51134. */
  51135. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  51136. const gl = this.gl;
  51137. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  51138. if ( depthTexture !== null ) {
  51139. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  51140. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  51141. // The multisample_render_to_texture extension doesn't work properly if there
  51142. // are midframe flushes and an external depth texture.
  51143. if ( ( this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) && renderTarget._autoAllocateDepthBuffer === true && renderTarget.multiview === false ) {
  51144. warn( 'WebGLBackend: Render-to-texture extension was disabled because an external texture was provided' );
  51145. }
  51146. renderTarget._autoAllocateDepthBuffer = false;
  51147. }
  51148. }
  51149. /**
  51150. * Inits a time stamp query for the given render context.
  51151. *
  51152. * @param {string} type - The type of the timestamp query.
  51153. * @param {string} uid - A unique identifier for the timestamp query.
  51154. */
  51155. initTimestampQuery( type, uid ) {
  51156. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  51157. if ( ! this.timestampQueryPool[ type ] ) {
  51158. // TODO: Variable maxQueries?
  51159. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  51160. }
  51161. const timestampQueryPool = this.timestampQueryPool[ type ];
  51162. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  51163. if ( baseOffset !== null ) {
  51164. timestampQueryPool.beginQuery( uid );
  51165. }
  51166. }
  51167. // timestamp utils
  51168. /**
  51169. * Prepares the timestamp buffer.
  51170. *
  51171. * @param {string} type - The type of the timestamp query.
  51172. * @param {string} uid - A unique identifier for the timestamp query.
  51173. */
  51174. prepareTimestampBuffer( type, uid ) {
  51175. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  51176. const timestampQueryPool = this.timestampQueryPool[ type ];
  51177. timestampQueryPool.endQuery( uid );
  51178. }
  51179. /**
  51180. * Returns the backend's rendering context.
  51181. *
  51182. * @return {WebGL2RenderingContext} The rendering context.
  51183. */
  51184. getContext() {
  51185. return this.gl;
  51186. }
  51187. /**
  51188. * This method is executed at the beginning of a render call and prepares
  51189. * the WebGL state for upcoming render calls
  51190. *
  51191. * @param {RenderContext} renderContext - The render context.
  51192. */
  51193. beginRender( renderContext ) {
  51194. const { state } = this;
  51195. const renderContextData = this.get( renderContext );
  51196. //
  51197. if ( renderContext.viewport ) {
  51198. this.updateViewport( renderContext );
  51199. } else {
  51200. const { width, height } = this.getDrawingBufferSize();
  51201. state.viewport( 0, 0, width, height );
  51202. }
  51203. if ( renderContext.scissor ) {
  51204. this.updateScissor( renderContext );
  51205. } else {
  51206. const { width, height } = this.getDrawingBufferSize();
  51207. state.scissor( 0, 0, width, height );
  51208. }
  51209. //
  51210. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  51211. renderContextData.previousContext = this._currentContext;
  51212. this._currentContext = renderContext;
  51213. this._setFramebuffer( renderContext );
  51214. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  51215. const occlusionQueryCount = renderContext.occlusionQueryCount;
  51216. if ( occlusionQueryCount > 0 ) {
  51217. // Get a reference to the array of objects with queries. The renderContextData property
  51218. // can be changed by another render pass before the async reading of all previous queries complete
  51219. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  51220. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  51221. renderContextData.lastOcclusionObject = null;
  51222. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  51223. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  51224. renderContextData.occlusionQueryIndex = 0;
  51225. } else if ( renderContextData.lastOcclusionObject !== undefined ) {
  51226. // invalidate if there is a stale query
  51227. renderContextData.lastOcclusionObject = undefined;
  51228. }
  51229. }
  51230. /**
  51231. * This method is executed at the end of a render call and finalizes work
  51232. * after draw calls.
  51233. *
  51234. * @param {RenderContext} renderContext - The render context.
  51235. */
  51236. finishRender( renderContext ) {
  51237. const { gl, state } = this;
  51238. const renderContextData = this.get( renderContext );
  51239. const previousContext = renderContextData.previousContext;
  51240. state.resetVertexState();
  51241. const occlusionQueryCount = renderContext.occlusionQueryCount;
  51242. if ( occlusionQueryCount > 0 ) {
  51243. const lastOcclusionObject = renderContextData.lastOcclusionObject;
  51244. if ( lastOcclusionObject && lastOcclusionObject.occlusionTest === true ) {
  51245. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  51246. }
  51247. this.resolveOccludedAsync( renderContext );
  51248. }
  51249. const textures = renderContext.textures;
  51250. if ( textures !== null ) {
  51251. for ( let i = 0; i < textures.length; i ++ ) {
  51252. const texture = textures[ i ];
  51253. if ( texture.generateMipmaps ) {
  51254. this.generateMipmaps( texture );
  51255. }
  51256. }
  51257. }
  51258. this._currentContext = previousContext;
  51259. this._resolveRenderTarget( renderContext );
  51260. if ( previousContext !== null ) {
  51261. this._setFramebuffer( previousContext );
  51262. if ( previousContext.viewport ) {
  51263. this.updateViewport( previousContext );
  51264. } else {
  51265. const { width, height } = this.getDrawingBufferSize();
  51266. state.viewport( 0, 0, width, height );
  51267. }
  51268. if ( previousContext.scissor ) {
  51269. this.updateScissor( previousContext );
  51270. } else {
  51271. const { width, height } = this.getDrawingBufferSize();
  51272. state.scissor( 0, 0, width, height );
  51273. }
  51274. }
  51275. this.prepareTimestampBuffer( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  51276. }
  51277. /**
  51278. * This method processes the result of occlusion queries and writes it
  51279. * into render context data.
  51280. *
  51281. * @async
  51282. * @param {RenderContext} renderContext - The render context.
  51283. */
  51284. resolveOccludedAsync( renderContext ) {
  51285. const renderContextData = this.get( renderContext );
  51286. // handle occlusion query results
  51287. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  51288. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  51289. const occluded = new WeakSet();
  51290. const { gl } = this;
  51291. renderContextData.currentOcclusionQueryObjects = null;
  51292. renderContextData.currentOcclusionQueries = null;
  51293. const check = () => {
  51294. let completed = true;
  51295. // check all queries and requeue as appropriate
  51296. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  51297. const query = currentOcclusionQueries[ i ];
  51298. if ( ! query ) continue;
  51299. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  51300. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  51301. currentOcclusionQueries[ i ] = null;
  51302. gl.deleteQuery( query );
  51303. } else {
  51304. completed = false;
  51305. }
  51306. }
  51307. if ( completed === false ) {
  51308. requestAnimationFrame( check );
  51309. } else {
  51310. renderContextData.occluded = occluded;
  51311. }
  51312. };
  51313. check();
  51314. }
  51315. }
  51316. /**
  51317. * Returns `true` if the given 3D object is fully occluded by other
  51318. * 3D objects in the scene.
  51319. *
  51320. * @param {RenderContext} renderContext - The render context.
  51321. * @param {Object3D} object - The 3D object to test.
  51322. * @return {boolean} Whether the 3D object is fully occluded or not.
  51323. */
  51324. isOccluded( renderContext, object ) {
  51325. const renderContextData = this.get( renderContext );
  51326. return renderContextData.occluded && renderContextData.occluded.has( object );
  51327. }
  51328. /**
  51329. * Updates the viewport with the values from the given render context.
  51330. *
  51331. * @param {RenderContext} renderContext - The render context.
  51332. */
  51333. updateViewport( renderContext ) {
  51334. const { state } = this;
  51335. const { x, y, width, height } = renderContext.viewportValue;
  51336. state.viewport( x, renderContext.height - height - y, width, height );
  51337. }
  51338. /**
  51339. * Updates the scissor with the values from the given render context.
  51340. *
  51341. * @param {RenderContext} renderContext - The render context.
  51342. */
  51343. updateScissor( renderContext ) {
  51344. const { state } = this;
  51345. const { x, y, width, height } = renderContext.scissorValue;
  51346. state.scissor( x, renderContext.height - height - y, width, height );
  51347. }
  51348. /**
  51349. * Defines the scissor test.
  51350. *
  51351. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  51352. */
  51353. setScissorTest( boolean ) {
  51354. const state = this.state;
  51355. state.setScissorTest( boolean );
  51356. }
  51357. /**
  51358. * Restores the WebGL state to its default and invalidates the internal state cache.
  51359. */
  51360. resetState() {
  51361. this.state.reset();
  51362. }
  51363. /**
  51364. * Returns the clear color and alpha into a single
  51365. * color object.
  51366. *
  51367. * @return {Color4} The clear color.
  51368. */
  51369. getClearColor() {
  51370. const clearColor = super.getClearColor();
  51371. // Since the canvas is always created with alpha: true,
  51372. // WebGL must always premultiply the clear color.
  51373. clearColor.r *= clearColor.a;
  51374. clearColor.g *= clearColor.a;
  51375. clearColor.b *= clearColor.a;
  51376. return clearColor;
  51377. }
  51378. /**
  51379. * Performs a clear operation.
  51380. *
  51381. * @param {boolean} color - Whether the color buffer should be cleared or not.
  51382. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  51383. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  51384. * @param {?Object} [descriptor=null] - The render context of the current set render target.
  51385. * @param {boolean} [setFrameBuffer=true] - Controls whether the intermediate framebuffer should be set or not.
  51386. * @param {boolean} [resolveRenderTarget=true] - Controls whether an active render target should be resolved
  51387. * or not. Only relevant for explicit clears.
  51388. */
  51389. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true, resolveRenderTarget = true ) {
  51390. const { gl, renderer } = this;
  51391. if ( descriptor === null ) {
  51392. const clearColor = this.getClearColor();
  51393. descriptor = {
  51394. textures: null,
  51395. clearColorValue: clearColor
  51396. };
  51397. }
  51398. //
  51399. let clear = 0;
  51400. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  51401. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  51402. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  51403. if ( clear !== 0 ) {
  51404. let clearColor;
  51405. if ( descriptor.clearColorValue ) {
  51406. clearColor = descriptor.clearColorValue;
  51407. } else {
  51408. clearColor = this.getClearColor();
  51409. }
  51410. const clearDepth = renderer.getClearDepth();
  51411. const clearStencil = renderer.getClearStencil();
  51412. if ( depth ) this.state.setDepthMask( true );
  51413. if ( descriptor.textures === null ) {
  51414. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  51415. gl.clear( clear );
  51416. } else {
  51417. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  51418. if ( color ) {
  51419. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  51420. if ( i === 0 ) {
  51421. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  51422. } else {
  51423. gl.clearBufferfv( gl.COLOR, i, [ 0, 0, 0, 1 ] );
  51424. }
  51425. }
  51426. }
  51427. if ( depth && stencil ) {
  51428. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, clearDepth, clearStencil );
  51429. } else if ( depth ) {
  51430. gl.clearBufferfv( gl.DEPTH, 0, [ clearDepth ] );
  51431. } else if ( stencil ) {
  51432. gl.clearBufferiv( gl.STENCIL, 0, [ clearStencil ] );
  51433. }
  51434. if ( setFrameBuffer && resolveRenderTarget ) this._resolveRenderTarget( descriptor );
  51435. // Restore the framebuffer of the active render pass when clearing an unrelated
  51436. // render target, so subsequent draws in the pass don't bind to the cleared target.
  51437. if ( setFrameBuffer && this._currentContext !== null && this._currentContext !== descriptor ) {
  51438. this._setFramebuffer( this._currentContext );
  51439. }
  51440. }
  51441. }
  51442. }
  51443. /**
  51444. * This method is executed at the beginning of a compute call and
  51445. * prepares the state for upcoming compute tasks.
  51446. *
  51447. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  51448. */
  51449. beginCompute( computeGroup ) {
  51450. const { state, gl } = this;
  51451. //
  51452. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  51453. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  51454. }
  51455. /**
  51456. * Executes a compute command for the given compute node.
  51457. *
  51458. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  51459. * @param {Node} computeNode - The compute node.
  51460. * @param {Array<BindGroup>} bindings - The bindings.
  51461. * @param {ComputePipeline} pipeline - The compute pipeline.
  51462. * @param {?number} [count=null] - The count of compute invocations. If `null`, the count is determined by the compute node.
  51463. */
  51464. compute( computeGroup, computeNode, bindings, pipeline, count = null ) {
  51465. const { state, gl } = this;
  51466. if ( this.discard === false ) {
  51467. // required here to handle async behaviour of render.compute()
  51468. state.enable( gl.RASTERIZER_DISCARD );
  51469. this.discard = true;
  51470. }
  51471. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  51472. const vaoKey = this._getVaoKey( attributes );
  51473. const vaoGPU = this.vaoCache[ vaoKey ];
  51474. if ( vaoGPU === undefined ) {
  51475. this.vaoCache[ vaoKey ] = this._createVao( attributes );
  51476. } else {
  51477. state.setVertexState( vaoGPU );
  51478. }
  51479. state.useProgram( programGPU );
  51480. this._bindUniforms( bindings );
  51481. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  51482. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  51483. gl.beginTransformFeedback( gl.POINTS );
  51484. count = ( count !== null ) ? count : computeNode.count;
  51485. if ( Array.isArray( count ) ) {
  51486. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not an array.' );
  51487. count = count[ 0 ];
  51488. } else if ( count && typeof count === 'object' && count.isIndirectStorageBufferAttribute ) {
  51489. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not IndirectStorageBufferAttribute' );
  51490. count = computeNode.count;
  51491. }
  51492. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  51493. gl.drawArraysInstanced( gl.POINTS, 0, 1, count );
  51494. } else {
  51495. gl.drawArrays( gl.POINTS, 0, count );
  51496. }
  51497. gl.endTransformFeedback();
  51498. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  51499. // switch active buffers
  51500. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  51501. const dualAttributeData = transformBuffers[ i ];
  51502. if ( dualAttributeData.pbo && this.has( dualAttributeData.pbo ) ) {
  51503. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  51504. }
  51505. dualAttributeData.switchBuffers();
  51506. }
  51507. }
  51508. /**
  51509. * This method is executed at the end of a compute call and
  51510. * finalizes work after compute tasks.
  51511. *
  51512. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  51513. */
  51514. finishCompute( computeGroup ) {
  51515. const { state, gl } = this;
  51516. this.discard = false;
  51517. state.disable( gl.RASTERIZER_DISCARD );
  51518. this.prepareTimestampBuffer( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  51519. if ( this._currentContext ) {
  51520. this._setFramebuffer( this._currentContext );
  51521. }
  51522. }
  51523. /**
  51524. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  51525. *
  51526. * @param {RenderContext} renderContext - The render context.
  51527. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  51528. *
  51529. * @private
  51530. */
  51531. _isRenderCameraDepthArray( renderContext ) {
  51532. return renderContext.depthTexture && renderContext.depthTexture.isArrayTexture && renderContext.camera.isArrayCamera;
  51533. }
  51534. /**
  51535. * Internal draw function.
  51536. *
  51537. * @private
  51538. * @param {Object3D} object - The object to render.
  51539. * @param {WebGLBufferRenderer} renderer - The internal renderer.
  51540. * @param {number} firstVertex - The first vertex to render.
  51541. * @param {number} vertexCount - The vertex count.
  51542. * @param {number} instanceCount - The intance count.
  51543. * @param {WebGLProgram} programGPU - The raw WebGL shader program.
  51544. */
  51545. _draw( object, renderer, firstVertex, vertexCount, instanceCount, programGPU ) {
  51546. if ( object.isBatchedMesh ) {
  51547. if ( this.hasFeature( 'WEBGL_multi_draw' ) === false ) {
  51548. const { gl } = this;
  51549. const drawIdLocation = gl.getUniformLocation( programGPU, 'nodeUniformDrawId' );
  51550. const starts = object._multiDrawStarts;
  51551. const counts = object._multiDrawCounts;
  51552. const drawCount = object._multiDrawCount;
  51553. for ( let i = 0; i < drawCount; i ++ ) {
  51554. gl.uniform1ui( drawIdLocation, i );
  51555. renderer.render( starts[ i ], counts[ i ] );
  51556. }
  51557. } else {
  51558. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  51559. }
  51560. } else if ( instanceCount > 1 ) {
  51561. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  51562. } else {
  51563. renderer.render( firstVertex, vertexCount );
  51564. }
  51565. }
  51566. /**
  51567. * Executes a draw command for the given render object.
  51568. *
  51569. * @param {RenderObject} renderObject - The render object to draw.
  51570. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  51571. */
  51572. draw( renderObject/*, info*/ ) {
  51573. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  51574. const { programGPU } = this.get( pipeline );
  51575. const { gl, state } = this;
  51576. const contextData = this.get( context );
  51577. const drawParams = renderObject.getDrawParameters();
  51578. if ( drawParams === null ) return;
  51579. //
  51580. this._bindUniforms( renderObject.getBindings() );
  51581. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinantAffine() < 0 );
  51582. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  51583. if ( context.mrt !== null && context.textures !== null ) {
  51584. state.setMRTBlending( context.textures, context.mrt, material );
  51585. }
  51586. state.useProgram( programGPU );
  51587. // vertex state
  51588. const attributes = renderObject.getAttributes();
  51589. const attributesData = this.get( attributes );
  51590. let vaoGPU = attributesData.vaoGPU;
  51591. if ( vaoGPU === undefined ) {
  51592. const vaoKey = this._getVaoKey( attributes );
  51593. vaoGPU = this.vaoCache[ vaoKey ];
  51594. if ( vaoGPU === undefined ) {
  51595. vaoGPU = this._createVao( attributes );
  51596. this.vaoCache[ vaoKey ] = vaoGPU;
  51597. attributesData.vaoGPU = vaoGPU;
  51598. }
  51599. }
  51600. const index = renderObject.getIndex();
  51601. const indexGPU = ( index !== null ) ? this.get( index ).bufferGPU : null;
  51602. state.setVertexState( vaoGPU, indexGPU );
  51603. //
  51604. const lastObject = contextData.lastOcclusionObject;
  51605. if ( lastObject !== object && lastObject !== undefined ) {
  51606. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  51607. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  51608. contextData.occlusionQueryIndex ++;
  51609. }
  51610. if ( object.occlusionTest === true ) {
  51611. const query = gl.createQuery();
  51612. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  51613. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  51614. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  51615. }
  51616. contextData.lastOcclusionObject = object;
  51617. }
  51618. //
  51619. const renderer = this.bufferRenderer;
  51620. if ( object.isPoints ) renderer.mode = gl.POINTS;
  51621. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  51622. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  51623. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  51624. else {
  51625. if ( material.wireframe === true ) {
  51626. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  51627. renderer.mode = gl.LINES;
  51628. } else {
  51629. renderer.mode = gl.TRIANGLES;
  51630. }
  51631. }
  51632. //
  51633. const { vertexCount, instanceCount } = drawParams;
  51634. let { firstVertex } = drawParams;
  51635. renderer.object = object;
  51636. if ( index !== null ) {
  51637. firstVertex *= index.array.BYTES_PER_ELEMENT;
  51638. const indexData = this.get( index );
  51639. renderer.index = index.count;
  51640. renderer.type = indexData.type;
  51641. } else {
  51642. renderer.index = 0;
  51643. }
  51644. if ( renderObject.camera.isArrayCamera === true && renderObject.camera.cameras.length > 0 && renderObject.camera.isMultiViewCamera === false ) {
  51645. const cameraData = this.get( renderObject.camera );
  51646. const cameras = renderObject.camera.cameras;
  51647. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  51648. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  51649. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  51650. const indexesGPU = [];
  51651. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  51652. const bufferGPU = gl.createBuffer();
  51653. data[ 0 ] = i;
  51654. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  51655. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  51656. indexesGPU.push( bufferGPU );
  51657. }
  51658. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  51659. }
  51660. let cameraIndexBufferIndex = 0;
  51661. bindingsSearch: for ( const bindGroup of renderObject.getBindings() ) {
  51662. for ( const binding of bindGroup.bindings ) {
  51663. if ( binding === cameraIndex ) break bindingsSearch;
  51664. if ( binding.isUniformsGroup || binding.isUniformBuffer ) cameraIndexBufferIndex ++;
  51665. }
  51666. }
  51667. const pixelRatio = this.renderer.getPixelRatio();
  51668. const renderTarget = this._currentContext.renderTarget;
  51669. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( this._currentContext );
  51670. const prevActiveCubeFace = this._currentContext.activeCubeFace;
  51671. if ( isRenderCameraDepthArray ) {
  51672. // Clear the depth texture
  51673. const textureData = this.get( renderTarget.depthTexture );
  51674. if ( textureData.clearedRenderId !== this.renderer._nodes.nodeFrame.renderId ) {
  51675. textureData.clearedRenderId = this.renderer._nodes.nodeFrame.renderId;
  51676. const { stencilBuffer } = renderTarget;
  51677. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  51678. this.renderer._activeCubeFace = i;
  51679. this._currentContext.activeCubeFace = i;
  51680. this._setFramebuffer( this._currentContext );
  51681. this.clear( false, true, stencilBuffer, this._currentContext, false, false );
  51682. }
  51683. this.renderer._activeCubeFace = prevActiveCubeFace;
  51684. this._currentContext.activeCubeFace = prevActiveCubeFace;
  51685. }
  51686. }
  51687. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  51688. const subCamera = cameras[ i ];
  51689. if ( object.layers.test( subCamera.layers ) ) {
  51690. if ( isRenderCameraDepthArray ) {
  51691. // Update the active layer
  51692. this.renderer._activeCubeFace = i;
  51693. this._currentContext.activeCubeFace = i;
  51694. this._setFramebuffer( this._currentContext );
  51695. }
  51696. const vp = subCamera.viewport;
  51697. if ( vp !== undefined ) {
  51698. const x = vp.x * pixelRatio;
  51699. const y = vp.y * pixelRatio;
  51700. const width = vp.width * pixelRatio;
  51701. const height = vp.height * pixelRatio;
  51702. state.viewport(
  51703. Math.floor( x ),
  51704. Math.floor( renderObject.context.height - height - y ),
  51705. Math.floor( width ),
  51706. Math.floor( height )
  51707. );
  51708. }
  51709. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexBufferIndex, cameraData.indexesGPU[ i ] );
  51710. this._draw( object, renderer, firstVertex, vertexCount, instanceCount, programGPU );
  51711. }
  51712. this._currentContext.activeCubeFace = prevActiveCubeFace;
  51713. this.renderer._activeCubeFace = prevActiveCubeFace;
  51714. }
  51715. } else {
  51716. this._draw( object, renderer, firstVertex, vertexCount, instanceCount, programGPU );
  51717. }
  51718. }
  51719. /**
  51720. * Explain why always null is returned.
  51721. *
  51722. * @param {RenderObject} renderObject - The render object.
  51723. * @return {boolean} Whether the render pipeline requires an update or not.
  51724. */
  51725. needsRenderUpdate( /*renderObject*/ ) {
  51726. return false;
  51727. }
  51728. /**
  51729. * Explain why no cache key is computed.
  51730. *
  51731. * @param {RenderObject} renderObject - The render object.
  51732. * @return {string} The cache key.
  51733. */
  51734. getRenderCacheKey( /*renderObject*/ ) {
  51735. return '';
  51736. }
  51737. // textures
  51738. /**
  51739. * Creates a default texture for the given texture that can be used
  51740. * as a placeholder until the actual texture is ready for usage.
  51741. *
  51742. * @param {Texture} texture - The texture to create a default texture for.
  51743. */
  51744. createDefaultTexture( texture ) {
  51745. this.textureUtils.createDefaultTexture( texture );
  51746. }
  51747. /**
  51748. * Defines a texture on the GPU for the given texture object.
  51749. *
  51750. * @param {Texture} texture - The texture.
  51751. * @param {Object} [options={}] - Optional configuration parameter.
  51752. */
  51753. createTexture( texture, options ) {
  51754. this.textureUtils.createTexture( texture, options );
  51755. }
  51756. /**
  51757. * Uploads the updated texture data to the GPU.
  51758. *
  51759. * @param {Texture} texture - The texture.
  51760. * @param {Object} [options={}] - Optional configuration parameter.
  51761. */
  51762. updateTexture( texture, options ) {
  51763. this.textureUtils.updateTexture( texture, options );
  51764. }
  51765. /**
  51766. * Generates mipmaps for the given texture.
  51767. *
  51768. * @param {Texture} texture - The texture.
  51769. */
  51770. generateMipmaps( texture ) {
  51771. this.textureUtils.generateMipmaps( texture );
  51772. }
  51773. /**
  51774. * Destroys the GPU data for the given texture object.
  51775. *
  51776. * @param {Texture} texture - The texture.
  51777. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  51778. */
  51779. destroyTexture( texture, isDefaultTexture = false ) {
  51780. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  51781. }
  51782. /**
  51783. * Returns texture data as a typed array.
  51784. *
  51785. * @async
  51786. * @param {Texture} texture - The texture to copy.
  51787. * @param {number} x - The x coordinate of the copy origin.
  51788. * @param {number} y - The y coordinate of the copy origin.
  51789. * @param {number} width - The width of the copy.
  51790. * @param {number} height - The height of the copy.
  51791. * @param {number} faceIndex - The face index.
  51792. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  51793. */
  51794. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  51795. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  51796. }
  51797. /**
  51798. * This method does nothing since WebGL 2 has no concept of samplers.
  51799. *
  51800. * @param {Sampler} binding - The sampler binding to update.
  51801. * @return {string} The current sampler key.
  51802. */
  51803. updateSampler( /*binding*/ ) {
  51804. return '';
  51805. }
  51806. // node builder
  51807. /**
  51808. * Returns a node builder for the given render object.
  51809. *
  51810. * @param {RenderObject} object - The render object.
  51811. * @param {Renderer} renderer - The renderer.
  51812. * @return {GLSLNodeBuilder} The node builder.
  51813. */
  51814. createNodeBuilder( object, renderer ) {
  51815. return new GLSLNodeBuilder( object, renderer );
  51816. }
  51817. // program
  51818. /**
  51819. * Creates a shader program from the given programmable stage.
  51820. *
  51821. * @param {ProgrammableStage} program - The programmable stage.
  51822. */
  51823. createProgram( program ) {
  51824. const gl = this.gl;
  51825. const { stage, code } = program;
  51826. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  51827. gl.shaderSource( shader, code );
  51828. gl.compileShader( shader );
  51829. this.set( program, {
  51830. shaderGPU: shader
  51831. } );
  51832. }
  51833. /**
  51834. * Destroys the shader program of the given programmable stage.
  51835. *
  51836. * @param {ProgrammableStage} program - The programmable stage.
  51837. */
  51838. destroyProgram( program ) {
  51839. this.delete( program );
  51840. }
  51841. /**
  51842. * Creates a render pipeline for the given render object.
  51843. *
  51844. * @param {RenderObject} renderObject - The render object.
  51845. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  51846. */
  51847. createRenderPipeline( renderObject, promises ) {
  51848. const gl = this.gl;
  51849. const pipeline = renderObject.pipeline;
  51850. // Program
  51851. const { fragmentProgram, vertexProgram } = pipeline;
  51852. const programGPU = gl.createProgram();
  51853. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  51854. const vertexShader = this.get( vertexProgram ).shaderGPU;
  51855. gl.attachShader( programGPU, fragmentShader );
  51856. gl.attachShader( programGPU, vertexShader );
  51857. gl.linkProgram( programGPU );
  51858. this.set( pipeline, {
  51859. programGPU,
  51860. fragmentShader,
  51861. vertexShader
  51862. } );
  51863. if ( promises !== null && this.parallel ) {
  51864. const p = new Promise( ( resolve /*, reject*/ ) => {
  51865. const parallel = this.parallel;
  51866. const checkStatus = () => {
  51867. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  51868. this._completeCompile( renderObject, pipeline );
  51869. resolve();
  51870. } else {
  51871. requestAnimationFrame( checkStatus );
  51872. }
  51873. };
  51874. checkStatus();
  51875. } );
  51876. promises.push( p );
  51877. return;
  51878. }
  51879. this._completeCompile( renderObject, pipeline );
  51880. }
  51881. /**
  51882. * Formats the source code of error messages.
  51883. *
  51884. * @private
  51885. * @param {string} string - The code.
  51886. * @param {number} errorLine - The error line.
  51887. * @return {string} The formatted code.
  51888. */
  51889. _handleSource( string, errorLine ) {
  51890. const lines = string.split( '\n' );
  51891. const lines2 = [];
  51892. const from = Math.max( errorLine - 6, 0 );
  51893. const to = Math.min( errorLine + 6, lines.length );
  51894. for ( let i = from; i < to; i ++ ) {
  51895. const line = i + 1;
  51896. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  51897. }
  51898. return lines2.join( '\n' );
  51899. }
  51900. /**
  51901. * Gets the shader compilation errors from the info log.
  51902. *
  51903. * @private
  51904. * @param {WebGL2RenderingContext} gl - The rendering context.
  51905. * @param {WebGLShader} shader - The WebGL shader object.
  51906. * @param {string} type - The shader type.
  51907. * @return {string} The shader errors.
  51908. */
  51909. _getShaderErrors( gl, shader, type ) {
  51910. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  51911. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  51912. const errors = shaderInfoLog.trim();
  51913. if ( status && errors === '' ) return '';
  51914. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  51915. if ( errorMatches ) {
  51916. const errorLine = parseInt( errorMatches[ 1 ] );
  51917. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  51918. } else {
  51919. return errors;
  51920. }
  51921. }
  51922. /**
  51923. * Logs shader compilation errors.
  51924. *
  51925. * @private
  51926. * @param {WebGLProgram} programGPU - The WebGL program.
  51927. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  51928. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  51929. */
  51930. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  51931. if ( this.renderer.debug.checkShaderErrors ) {
  51932. const gl = this.gl;
  51933. const programInfoLog = gl.getProgramInfoLog( programGPU ) || '';
  51934. const programLog = programInfoLog.trim();
  51935. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  51936. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  51937. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  51938. } else {
  51939. // default error reporting
  51940. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  51941. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  51942. error(
  51943. 'WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  51944. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  51945. 'Program Info Log: ' + programLog + '\n' +
  51946. vertexErrors + '\n' +
  51947. fragmentErrors
  51948. );
  51949. }
  51950. } else if ( programLog !== '' ) {
  51951. warn( 'WebGLProgram: Program Info Log:', programLog );
  51952. }
  51953. }
  51954. }
  51955. /**
  51956. * Completes the shader program setup for the given render object.
  51957. *
  51958. * @private
  51959. * @param {RenderObject} renderObject - The render object.
  51960. * @param {RenderPipeline} pipeline - The render pipeline.
  51961. */
  51962. _completeCompile( renderObject, pipeline ) {
  51963. const { state, gl } = this;
  51964. const pipelineData = this.get( pipeline );
  51965. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  51966. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  51967. this._logProgramError( programGPU, fragmentShader, vertexShader );
  51968. }
  51969. state.useProgram( programGPU );
  51970. // Bindings
  51971. const bindings = renderObject.getBindings();
  51972. this._setupBindings( bindings, programGPU );
  51973. //
  51974. this.set( pipeline, {
  51975. programGPU,
  51976. pipeline: programGPU
  51977. } );
  51978. }
  51979. /**
  51980. * Creates a compute pipeline for the given compute node.
  51981. *
  51982. * @param {ComputePipeline} computePipeline - The compute pipeline.
  51983. * @param {Array<BindGroup>} bindings - The bindings.
  51984. */
  51985. createComputePipeline( computePipeline, bindings ) {
  51986. const { state, gl } = this;
  51987. // Program
  51988. const fragmentProgram = {
  51989. stage: 'fragment',
  51990. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  51991. };
  51992. this.createProgram( fragmentProgram );
  51993. const { computeProgram } = computePipeline;
  51994. const programGPU = gl.createProgram();
  51995. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  51996. const vertexShader = this.get( computeProgram ).shaderGPU;
  51997. const transforms = computeProgram.transforms;
  51998. const transformVaryingNames = [];
  51999. const transformAttributeNodes = [];
  52000. for ( let i = 0; i < transforms.length; i ++ ) {
  52001. const transform = transforms[ i ];
  52002. transformVaryingNames.push( transform.varyingName );
  52003. transformAttributeNodes.push( transform.attributeNode );
  52004. }
  52005. gl.attachShader( programGPU, fragmentShader );
  52006. gl.attachShader( programGPU, vertexShader );
  52007. gl.transformFeedbackVaryings(
  52008. programGPU,
  52009. transformVaryingNames,
  52010. gl.SEPARATE_ATTRIBS
  52011. );
  52012. gl.linkProgram( programGPU );
  52013. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  52014. this._logProgramError( programGPU, fragmentShader, vertexShader );
  52015. }
  52016. state.useProgram( programGPU );
  52017. // Bindings
  52018. this._setupBindings( bindings, programGPU );
  52019. const attributeNodes = computeProgram.attributes;
  52020. const attributes = [];
  52021. const transformBuffers = [];
  52022. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  52023. const attribute = attributeNodes[ i ].node.attribute;
  52024. attributes.push( attribute );
  52025. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  52026. }
  52027. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  52028. const attribute = transformAttributeNodes[ i ].attribute;
  52029. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  52030. const attributeData = this.get( attribute );
  52031. transformBuffers.push( attributeData );
  52032. }
  52033. //
  52034. this.set( computePipeline, {
  52035. programGPU,
  52036. transformBuffers,
  52037. attributes
  52038. } );
  52039. }
  52040. /**
  52041. * Creates bindings from the given bind group definition.
  52042. *
  52043. * @param {BindGroup} bindGroup - The bind group.
  52044. * @param {Array<BindGroup>} bindings - Array of bind groups.
  52045. * @param {number} cacheIndex - The cache index.
  52046. * @param {number} version - The version.
  52047. */
  52048. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  52049. if ( this._knownBindings.has( bindings ) === false ) {
  52050. this._knownBindings.add( bindings );
  52051. let uniformBuffers = 0;
  52052. let textures = 0;
  52053. for ( const bindGroup of bindings ) {
  52054. this.set( bindGroup, {
  52055. textures: textures,
  52056. uniformBuffers: uniformBuffers
  52057. } );
  52058. for ( const binding of bindGroup.bindings ) {
  52059. if ( binding.isUniformBuffer ) uniformBuffers ++;
  52060. if ( binding.isSampledTexture ) textures ++;
  52061. }
  52062. }
  52063. }
  52064. this.updateBindings( bindGroup, bindings );
  52065. }
  52066. /**
  52067. * Updates the given bind group definition.
  52068. *
  52069. * @param {BindGroup} bindGroup - The bind group.
  52070. * @param {Array<BindGroup>} bindings - Array of bind groups.
  52071. * @param {number} cacheIndex - The cache index.
  52072. * @param {number} version - The version.
  52073. */
  52074. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  52075. const { gl } = this;
  52076. for ( const binding of bindGroup.bindings ) {
  52077. const map = this.get( binding );
  52078. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  52079. const array = binding.buffer;
  52080. const bufferGPU = map.bufferGPU;
  52081. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  52082. // update
  52083. const updateRanges = binding.updateRanges;
  52084. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  52085. if ( updateRanges.length === 0 ) {
  52086. gl.bufferData( gl.UNIFORM_BUFFER, array, gl.DYNAMIC_DRAW );
  52087. } else {
  52088. const isTyped = isTypedArray( array );
  52089. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  52090. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  52091. const range = updateRanges[ i ];
  52092. const dataOffset = range.start * byteOffsetFactor;
  52093. const size = range.count * byteOffsetFactor;
  52094. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  52095. gl.bufferSubData( gl.UNIFORM_BUFFER, bufferOffset, array, dataOffset, size );
  52096. }
  52097. }
  52098. this.set( binding, map );
  52099. } else if ( binding.isSampledTexture ) {
  52100. const { textureGPU, glTextureType } = this.get( binding.texture );
  52101. map.textureGPU = textureGPU;
  52102. map.glTextureType = glTextureType;
  52103. this.set( binding, map );
  52104. }
  52105. }
  52106. }
  52107. /**
  52108. * Updates a buffer binding.
  52109. *
  52110. * @param {Buffer} binding - The buffer binding to update.
  52111. */
  52112. updateBinding( binding ) {
  52113. const gl = this.gl;
  52114. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  52115. const bindingData = this.get( binding );
  52116. const bufferGPU = bindingData.bufferGPU;
  52117. const array = binding.buffer;
  52118. const updateRanges = binding.updateRanges;
  52119. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  52120. if ( updateRanges.length === 0 ) {
  52121. gl.bufferData( gl.UNIFORM_BUFFER, array, gl.DYNAMIC_DRAW );
  52122. } else {
  52123. const isTyped = isTypedArray( array );
  52124. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  52125. // Update ranges arrive sorted and non-overlapping which makes
  52126. // it easy to merge contiguous ranges.
  52127. let start = updateRanges[ 0 ].start; // start of the current merged range
  52128. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  52129. const range = updateRanges[ i ];
  52130. const next = updateRanges[ i + 1 ];
  52131. const end = range.start + range.count; // exclusive end of the current range
  52132. // keep merging while the next range is contiguous
  52133. if ( next !== undefined && next.start === end ) continue;
  52134. // write the merged range
  52135. const dataOffset = start * byteOffsetFactor;
  52136. const size = ( end - start ) * byteOffsetFactor;
  52137. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  52138. gl.bufferSubData( gl.UNIFORM_BUFFER, bufferOffset, array, dataOffset, size );
  52139. // start next if possible
  52140. if ( next !== undefined ) start = next.start;
  52141. }
  52142. }
  52143. }
  52144. }
  52145. // attributes
  52146. /**
  52147. * Creates a uniform buffer.
  52148. *
  52149. * @param {Buffer} uniformBuffer - The uniform buffer.
  52150. */
  52151. createUniformBuffer( uniformBuffer ) {
  52152. const uniformBufferData = this.get( uniformBuffer );
  52153. if ( uniformBufferData.bufferGPU === undefined ) {
  52154. const gl = this.gl;
  52155. const array = uniformBuffer.buffer;
  52156. uniformBufferData.bufferGPU = gl.createBuffer();
  52157. gl.bindBuffer( gl.UNIFORM_BUFFER, uniformBufferData.bufferGPU );
  52158. gl.bufferData( gl.UNIFORM_BUFFER, array.byteLength, gl.DYNAMIC_DRAW );
  52159. }
  52160. }
  52161. /**
  52162. * Destroys the GPU data for the given uniform buffer.
  52163. *
  52164. * @param {Buffer} uniformBuffer - The uniform buffer.
  52165. */
  52166. destroyUniformBuffer( uniformBuffer ) {
  52167. const uniformBufferData = this.get( uniformBuffer );
  52168. this.gl.deleteBuffer( uniformBufferData.bufferGPU );
  52169. this.delete( uniformBuffer );
  52170. }
  52171. /**
  52172. * Creates the GPU buffer of an indexed shader attribute.
  52173. *
  52174. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  52175. */
  52176. createIndexAttribute( attribute ) {
  52177. const gl = this.gl;
  52178. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  52179. }
  52180. /**
  52181. * Creates the GPU buffer of a shader attribute.
  52182. *
  52183. * @param {BufferAttribute} attribute - The buffer attribute.
  52184. */
  52185. createAttribute( attribute ) {
  52186. if ( this.has( attribute ) ) return;
  52187. const gl = this.gl;
  52188. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  52189. }
  52190. /**
  52191. * Creates the GPU buffer of a storage attribute.
  52192. *
  52193. * @param {BufferAttribute} attribute - The buffer attribute.
  52194. */
  52195. createStorageAttribute( attribute ) {
  52196. if ( this.has( attribute ) ) return;
  52197. const gl = this.gl;
  52198. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  52199. }
  52200. /**
  52201. * Updates the GPU buffer of a shader attribute.
  52202. *
  52203. * @param {BufferAttribute} attribute - The buffer attribute to update.
  52204. */
  52205. updateAttribute( attribute ) {
  52206. this.attributeUtils.updateAttribute( attribute );
  52207. }
  52208. /**
  52209. * Destroys the GPU buffer of a shader attribute.
  52210. *
  52211. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  52212. */
  52213. destroyAttribute( attribute ) {
  52214. this.attributeUtils.destroyAttribute( attribute );
  52215. }
  52216. /**
  52217. * Checks if the given feature is supported by the backend.
  52218. *
  52219. * @param {string} name - The feature's name.
  52220. * @return {boolean} Whether the feature is supported or not.
  52221. */
  52222. hasFeature( name ) {
  52223. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  52224. const extensions = this.extensions;
  52225. for ( let i = 0; i < keysMatching.length; i ++ ) {
  52226. if ( extensions.has( keysMatching[ i ] ) ) return true;
  52227. }
  52228. return false;
  52229. }
  52230. /**
  52231. * Copies data of the given source texture to the given destination texture.
  52232. *
  52233. * @param {Texture} srcTexture - The source texture.
  52234. * @param {Texture} dstTexture - The destination texture.
  52235. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  52236. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  52237. * @param {number} [srcLevel=0] - The source mip level to copy from.
  52238. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  52239. */
  52240. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  52241. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  52242. }
  52243. /**
  52244. * Copies the current bound framebuffer to the given texture.
  52245. *
  52246. * @param {Texture} texture - The destination texture.
  52247. * @param {RenderContext} renderContext - The render context.
  52248. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  52249. */
  52250. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  52251. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  52252. }
  52253. /**
  52254. * Checks if the given compatibility is supported by the backend.
  52255. *
  52256. * @param {string} name - The compatibility name.
  52257. * @return {boolean} Whether the compatibility is supported or not.
  52258. */
  52259. hasCompatibility( name ) {
  52260. if ( name === Compatibility.TEXTURE_COMPARE ) return true;
  52261. return super.hasCompatibility( name );
  52262. }
  52263. /**
  52264. * Initializes the render target defined in the given render context.
  52265. *
  52266. * @param {RenderContext} renderContext - The render context.
  52267. */
  52268. initRenderTarget( renderContext ) {
  52269. const { gl, state } = this;
  52270. this._setFramebuffer( renderContext );
  52271. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  52272. }
  52273. /**
  52274. * Configures the active framebuffer from the given render context.
  52275. *
  52276. * @private
  52277. * @param {RenderContext} descriptor - The render context.
  52278. */
  52279. _setFramebuffer( descriptor ) {
  52280. const { gl, state } = this;
  52281. let currentFrameBuffer = null;
  52282. if ( descriptor.textures !== null ) {
  52283. const renderTarget = descriptor.renderTarget;
  52284. const renderTargetContextData = this.get( renderTarget );
  52285. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  52286. const isCube = renderTarget.isCubeRenderTarget === true;
  52287. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  52288. const isRenderTargetArray = renderTarget.depth > 1;
  52289. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  52290. const _hasExternalTextures = ( isXRRenderTarget === true && renderTarget._hasExternalTextures === true );
  52291. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  52292. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  52293. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  52294. const multiviewExt = this.extensions.get( 'OVR_multiview2' );
  52295. const useMultisampledRTT = this._useMultisampledExtension( renderTarget );
  52296. const cacheKey = getCacheKey( descriptor );
  52297. let fb;
  52298. if ( isCube ) {
  52299. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  52300. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  52301. } else if ( isXRRenderTarget && _hasExternalTextures === false ) {
  52302. fb = this._xrFramebuffer;
  52303. } else {
  52304. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  52305. fb = renderTargetContextData.framebuffers[ cacheKey ];
  52306. }
  52307. if ( fb === undefined ) {
  52308. fb = gl.createFramebuffer();
  52309. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  52310. const textures = descriptor.textures;
  52311. const depthInvalidationArray = [];
  52312. if ( isCube ) {
  52313. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  52314. const { textureGPU } = this.get( textures[ 0 ] );
  52315. const cubeFace = this.renderer._activeCubeFace;
  52316. const mipLevel = this.renderer._activeMipmapLevel;
  52317. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, mipLevel );
  52318. } else {
  52319. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  52320. for ( let i = 0; i < textures.length; i ++ ) {
  52321. const texture = textures[ i ];
  52322. const textureData = this.get( texture );
  52323. textureData.renderTarget = descriptor.renderTarget;
  52324. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  52325. const attachment = gl.COLOR_ATTACHMENT0 + i;
  52326. if ( renderTarget.multiview ) {
  52327. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, samples, 0, 2 );
  52328. } else if ( isRenderTarget3D || isRenderTargetArray ) {
  52329. const layer = this.renderer._activeCubeFace;
  52330. const mipLevel = this.renderer._activeMipmapLevel;
  52331. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, mipLevel, layer );
  52332. } else {
  52333. if ( useMultisampledRTT ) {
  52334. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  52335. } else {
  52336. const mipLevel = this.renderer._activeMipmapLevel;
  52337. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, mipLevel );
  52338. }
  52339. }
  52340. }
  52341. }
  52342. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  52343. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  52344. const renderbuffer = gl.createRenderbuffer();
  52345. this.textureUtils.setupRenderBufferStorage( renderbuffer, descriptor, 0, useMultisampledRTT );
  52346. renderTargetContextData.xrDepthRenderbuffer = renderbuffer;
  52347. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  52348. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  52349. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  52350. } else {
  52351. if ( descriptor.depthTexture !== null ) {
  52352. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  52353. const textureData = this.get( descriptor.depthTexture );
  52354. textureData.renderTarget = descriptor.renderTarget;
  52355. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  52356. if ( renderTarget.multiview ) {
  52357. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  52358. } else if ( _hasExternalTextures && useMultisampledRTT ) {
  52359. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  52360. } else {
  52361. if ( descriptor.depthTexture.isArrayTexture ) {
  52362. const layer = this.renderer._activeCubeFace;
  52363. gl.framebufferTextureLayer( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, layer );
  52364. } else if ( descriptor.depthTexture.isCubeTexture ) {
  52365. const cubeFace = this.renderer._activeCubeFace;
  52366. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureData.textureGPU, 0 );
  52367. } else {
  52368. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  52369. }
  52370. }
  52371. }
  52372. }
  52373. renderTargetContextData.depthInvalidationArray = depthInvalidationArray;
  52374. } else {
  52375. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( descriptor );
  52376. if ( isRenderCameraDepthArray ) {
  52377. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  52378. const layer = this.renderer._activeCubeFace;
  52379. const depthData = this.get( descriptor.depthTexture );
  52380. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  52381. gl.framebufferTextureLayer(
  52382. gl.FRAMEBUFFER,
  52383. depthStyle,
  52384. depthData.textureGPU,
  52385. 0,
  52386. layer
  52387. );
  52388. }
  52389. // rebind external XR textures
  52390. if ( ( isXRRenderTarget || useMultisampledRTT || renderTarget.multiview ) && ( renderTarget._isOpaqueFramebuffer !== true ) ) {
  52391. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  52392. // rebind color
  52393. const textureData = this.get( descriptor.textures[ 0 ] );
  52394. if ( renderTarget.multiview ) {
  52395. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, textureData.textureGPU, 0, samples, 0, 2 );
  52396. } else if ( useMultisampledRTT ) {
  52397. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  52398. } else {
  52399. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  52400. }
  52401. // rebind depth
  52402. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  52403. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  52404. const renderbuffer = renderTargetContextData.xrDepthRenderbuffer;
  52405. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  52406. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  52407. } else {
  52408. const textureData = this.get( descriptor.depthTexture );
  52409. if ( renderTarget.multiview ) {
  52410. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  52411. } else if ( useMultisampledRTT ) {
  52412. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  52413. } else {
  52414. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  52415. }
  52416. }
  52417. }
  52418. }
  52419. if ( samples > 0 && useMultisampledRTT === false && ! renderTarget.multiview ) {
  52420. if ( msaaFb === undefined ) {
  52421. msaaFb = gl.createFramebuffer();
  52422. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  52423. const msaaRenderbuffers = [];
  52424. const textures = descriptor.textures;
  52425. for ( let i = 0; i < textures.length; i ++ ) {
  52426. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  52427. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  52428. const texture = descriptor.textures[ i ];
  52429. const textureData = this.get( texture );
  52430. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  52431. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  52432. }
  52433. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  52434. renderTargetContextData.msaaFrameBuffer = msaaFb;
  52435. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  52436. if ( depthBuffer && depthRenderbuffer === undefined ) {
  52437. depthRenderbuffer = gl.createRenderbuffer();
  52438. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor, samples );
  52439. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  52440. }
  52441. }
  52442. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  52443. } else {
  52444. currentFrameBuffer = fb;
  52445. }
  52446. state.drawBuffers( descriptor, fb );
  52447. }
  52448. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  52449. }
  52450. /**
  52451. * Computes the VAO key for the given index and attributes.
  52452. *
  52453. * @private
  52454. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  52455. * @return {string} The VAO key.
  52456. */
  52457. _getVaoKey( attributes ) {
  52458. let key = '';
  52459. for ( let i = 0; i < attributes.length; i ++ ) {
  52460. const attributeData = this.get( attributes[ i ] );
  52461. key += ':' + attributeData.id;
  52462. }
  52463. return key;
  52464. }
  52465. /**
  52466. * Creates a VAO from the index and attributes.
  52467. *
  52468. * @private
  52469. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  52470. * @return {Object} The VAO data.
  52471. */
  52472. _createVao( attributes ) {
  52473. const { gl } = this;
  52474. const vaoGPU = gl.createVertexArray();
  52475. gl.bindVertexArray( vaoGPU );
  52476. for ( let i = 0; i < attributes.length; i ++ ) {
  52477. const attribute = attributes[ i ];
  52478. const attributeData = this.get( attribute );
  52479. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  52480. gl.enableVertexAttribArray( i );
  52481. let stride, offset;
  52482. if ( attribute.isInterleavedBufferAttribute === true ) {
  52483. stride = attribute.data.stride * attributeData.bytesPerElement;
  52484. offset = attribute.offset * attributeData.bytesPerElement;
  52485. } else {
  52486. stride = 0;
  52487. offset = 0;
  52488. }
  52489. if ( attributeData.isInteger ) {
  52490. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  52491. } else {
  52492. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  52493. }
  52494. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  52495. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  52496. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  52497. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  52498. }
  52499. }
  52500. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  52501. return vaoGPU;
  52502. }
  52503. /**
  52504. * Creates a transform feedback from the given transform buffers.
  52505. *
  52506. * @private
  52507. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  52508. * @return {WebGLTransformFeedback} The transform feedback.
  52509. */
  52510. _getTransformFeedback( transformBuffers ) {
  52511. let key = '';
  52512. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  52513. key += ':' + transformBuffers[ i ].id;
  52514. }
  52515. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  52516. if ( transformFeedbackGPU !== undefined ) {
  52517. return transformFeedbackGPU;
  52518. }
  52519. const { gl } = this;
  52520. transformFeedbackGPU = gl.createTransformFeedback();
  52521. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  52522. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  52523. const attributeData = transformBuffers[ i ];
  52524. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  52525. }
  52526. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  52527. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  52528. return transformFeedbackGPU;
  52529. }
  52530. /**
  52531. * Setups the given bindings.
  52532. *
  52533. * @private
  52534. * @param {Array<BindGroup>} bindings - The bindings.
  52535. * @param {WebGLProgram} programGPU - The WebGL program.
  52536. */
  52537. _setupBindings( bindings, programGPU ) {
  52538. const gl = this.gl;
  52539. let uniformBuffers = 0;
  52540. let textures = 0;
  52541. for ( const bindGroup of bindings ) {
  52542. for ( const binding of bindGroup.bindings ) {
  52543. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  52544. const index = uniformBuffers ++;
  52545. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  52546. gl.uniformBlockBinding( programGPU, location, index );
  52547. } else if ( binding.isSampledTexture ) {
  52548. const index = textures ++;
  52549. const location = gl.getUniformLocation( programGPU, binding.name );
  52550. gl.uniform1i( location, index );
  52551. }
  52552. }
  52553. }
  52554. }
  52555. /**
  52556. * Binds the given uniforms.
  52557. *
  52558. * @private
  52559. * @param {Array<BindGroup>} bindings - The bindings.
  52560. */
  52561. _bindUniforms( bindings ) {
  52562. const { gl, state } = this;
  52563. let uniformBuffers = 0;
  52564. let textures = 0;
  52565. for ( const bindGroup of bindings ) {
  52566. for ( const binding of bindGroup.bindings ) {
  52567. const bindingData = this.get( binding );
  52568. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  52569. const index = uniformBuffers ++;
  52570. // TODO USE bindBufferRange to group multiple uniform buffers
  52571. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  52572. } else if ( binding.isSampledTexture ) {
  52573. const index = textures ++;
  52574. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  52575. }
  52576. }
  52577. }
  52578. }
  52579. /**
  52580. * The method ensures multisampled render targets are resolved.
  52581. *
  52582. * @private
  52583. * @param {RenderContext} renderContext - The render context.
  52584. */
  52585. _resolveRenderTarget( renderContext ) {
  52586. const { gl, state } = this;
  52587. const renderTarget = renderContext.renderTarget;
  52588. if ( renderContext.textures !== null && renderTarget ) {
  52589. const renderTargetContextData = this.get( renderTarget );
  52590. if ( renderTarget.samples > 0 && this._useMultisampledExtension( renderTarget ) === false ) {
  52591. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  52592. let mask = renderTarget.resolveColorBuffer === false ? 0 : gl.COLOR_BUFFER_BIT;
  52593. if ( renderTarget.resolveDepthBuffer ) {
  52594. if ( renderTarget.depthBuffer ) mask |= gl.DEPTH_BUFFER_BIT;
  52595. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= gl.STENCIL_BUFFER_BIT;
  52596. }
  52597. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  52598. const msaaRenderbuffers = renderTargetContextData.msaaRenderbuffers;
  52599. const textures = renderContext.textures;
  52600. const isMRT = textures.length > 1;
  52601. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  52602. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  52603. if ( isMRT ) {
  52604. // blitFramebuffer() can only copy/resolve the first color attachment of a framebuffer. When using MRT,
  52605. // the engine temporarily removes all attachments and then configures each attachment for the resolve.
  52606. for ( let i = 0; i < textures.length; i ++ ) {
  52607. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, null );
  52608. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, null, 0 );
  52609. }
  52610. }
  52611. for ( let i = 0; i < textures.length; i ++ ) {
  52612. if ( isMRT ) {
  52613. // configure attachment for resolve
  52614. const { textureGPU } = this.get( textures[ i ] );
  52615. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  52616. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0 );
  52617. }
  52618. if ( renderContext.scissor ) {
  52619. const { x, y, width, height } = renderContext.scissorValue;
  52620. const viewY = renderContext.height - height - y;
  52621. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  52622. } else {
  52623. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  52624. }
  52625. }
  52626. if ( isMRT ) {
  52627. // restore attachments
  52628. for ( let i = 0; i < textures.length; i ++ ) {
  52629. const { textureGPU } = this.get( textures[ i ] );
  52630. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  52631. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, textureGPU, 0 );
  52632. }
  52633. }
  52634. if ( this._supportsInvalidateFramebuffer === true ) {
  52635. if ( renderTarget.storeMultisampledColorBuffer === false ) {
  52636. for ( let i = 0; i < textures.length; i ++ ) {
  52637. _invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  52638. }
  52639. }
  52640. if ( renderTarget.depthBuffer && renderTarget.storeMultisampledDepthBuffer === false ) {
  52641. _invalidationArray.push( renderTarget.stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  52642. }
  52643. if ( _invalidationArray.length > 0 ) {
  52644. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, _invalidationArray );
  52645. _invalidationArray.length = 0;
  52646. }
  52647. }
  52648. } else if ( renderTarget.storeMultisampledDepthBuffer === false && renderTargetContextData.framebuffers ) {
  52649. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  52650. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  52651. gl.invalidateFramebuffer( gl.DRAW_FRAMEBUFFER, renderTargetContextData.depthInvalidationArray );
  52652. }
  52653. }
  52654. }
  52655. /**
  52656. * Returns `true` if the `WEBGL_multisampled_render_to_texture` extension
  52657. * should be used when MSAA is enabled.
  52658. *
  52659. * @private
  52660. * @param {RenderTarget} renderTarget - The render target that should be multisampled.
  52661. * @return {boolean} Whether to use the `WEBGL_multisampled_render_to_texture` extension for MSAA or not.
  52662. */
  52663. _useMultisampledExtension( renderTarget ) {
  52664. if ( renderTarget.multiview === true ) {
  52665. return true;
  52666. }
  52667. return renderTarget.samples > 0 && this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTarget._autoAllocateDepthBuffer !== false;
  52668. }
  52669. /**
  52670. * Frees internal resources.
  52671. */
  52672. dispose() {
  52673. if ( this.textureUtils !== null ) this.textureUtils.dispose();
  52674. const extension = this.extensions.get( 'WEBGL_lose_context' );
  52675. if ( extension ) extension.loseContext();
  52676. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  52677. }
  52678. }
  52679. const GPUPrimitiveTopology = {
  52680. PointList: 'point-list',
  52681. LineList: 'line-list',
  52682. LineStrip: 'line-strip',
  52683. TriangleList: 'triangle-list'};
  52684. const GPUShaderStage = ( typeof self !== 'undefined' && self.GPUShaderStage ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  52685. const GPUCompareFunction = {
  52686. Never: 'never',
  52687. Less: 'less',
  52688. Equal: 'equal',
  52689. LessEqual: 'less-equal',
  52690. Greater: 'greater',
  52691. NotEqual: 'not-equal',
  52692. GreaterEqual: 'greater-equal',
  52693. Always: 'always'
  52694. };
  52695. const GPUStoreOp = {
  52696. Store: 'store',
  52697. Discard: 'discard'
  52698. };
  52699. const GPULoadOp = {
  52700. Load: 'load',
  52701. Clear: 'clear'
  52702. };
  52703. const GPUFrontFace = {
  52704. CCW: 'ccw',
  52705. CW: 'cw'
  52706. };
  52707. const GPUCullMode = {
  52708. None: 'none',
  52709. Back: 'back'
  52710. };
  52711. const GPUIndexFormat = {
  52712. Uint16: 'uint16',
  52713. Uint32: 'uint32'
  52714. };
  52715. const GPUTextureFormat = {
  52716. // 8-bit formats
  52717. R8Unorm: 'r8unorm',
  52718. R8Snorm: 'r8snorm',
  52719. R8Uint: 'r8uint',
  52720. R8Sint: 'r8sint',
  52721. // 16-bit formats
  52722. R16Uint: 'r16uint',
  52723. R16Sint: 'r16sint',
  52724. R16Float: 'r16float',
  52725. RG8Unorm: 'rg8unorm',
  52726. RG8Snorm: 'rg8snorm',
  52727. RG8Uint: 'rg8uint',
  52728. RG8Sint: 'rg8sint',
  52729. R16Unorm: 'r16unorm',
  52730. R16Snorm: 'r16snorm',
  52731. // 32-bit formats
  52732. R32Uint: 'r32uint',
  52733. R32Sint: 'r32sint',
  52734. R32Float: 'r32float',
  52735. RG16Uint: 'rg16uint',
  52736. RG16Sint: 'rg16sint',
  52737. RG16Float: 'rg16float',
  52738. RGBA8Unorm: 'rgba8unorm',
  52739. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  52740. RGBA8Snorm: 'rgba8snorm',
  52741. RGBA8Uint: 'rgba8uint',
  52742. RGBA8Sint: 'rgba8sint',
  52743. BGRA8Unorm: 'bgra8unorm',
  52744. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  52745. RG16Unorm: 'rg16unorm',
  52746. RG16Snorm: 'rg16snorm',
  52747. // Packed 32-bit formats
  52748. RGB9E5UFloat: 'rgb9e5ufloat',
  52749. RGB10A2Unorm: 'rgb10a2unorm',
  52750. RG11B10UFloat: 'rg11b10ufloat',
  52751. // 64-bit formats
  52752. RG32Uint: 'rg32uint',
  52753. RG32Sint: 'rg32sint',
  52754. RG32Float: 'rg32float',
  52755. RGBA16Uint: 'rgba16uint',
  52756. RGBA16Sint: 'rgba16sint',
  52757. RGBA16Float: 'rgba16float',
  52758. RGBA16Unorm: 'rgba16unorm',
  52759. RGBA16Snorm: 'rgba16snorm',
  52760. // 128-bit formats
  52761. RGBA32Uint: 'rgba32uint',
  52762. RGBA32Sint: 'rgba32sint',
  52763. RGBA32Float: 'rgba32float',
  52764. Depth16Unorm: 'depth16unorm',
  52765. Depth24Plus: 'depth24plus',
  52766. Depth24PlusStencil8: 'depth24plus-stencil8',
  52767. Depth32Float: 'depth32float',
  52768. // 'depth32float-stencil8' extension
  52769. Depth32FloatStencil8: 'depth32float-stencil8',
  52770. // BC compressed formats usable if 'texture-compression-bc' is both
  52771. // supported by the device/user agent and enabled in requestDevice.
  52772. BC1RGBAUnorm: 'bc1-rgba-unorm',
  52773. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  52774. BC2RGBAUnorm: 'bc2-rgba-unorm',
  52775. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  52776. BC3RGBAUnorm: 'bc3-rgba-unorm',
  52777. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  52778. BC4RUnorm: 'bc4-r-unorm',
  52779. BC4RSnorm: 'bc4-r-snorm',
  52780. BC5RGUnorm: 'bc5-rg-unorm',
  52781. BC5RGSnorm: 'bc5-rg-snorm',
  52782. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  52783. BC6HRGBFloat: 'bc6h-rgb-float',
  52784. BC7RGBAUnorm: 'bc7-rgba-unorm',
  52785. BC7RGBAUnormSRGB: 'bc7-rgba-unorm-srgb',
  52786. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  52787. // supported by the device/user agent and enabled in requestDevice.
  52788. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  52789. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  52790. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  52791. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  52792. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  52793. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  52794. EACR11Unorm: 'eac-r11unorm',
  52795. EACR11Snorm: 'eac-r11snorm',
  52796. EACRG11Unorm: 'eac-rg11unorm',
  52797. EACRG11Snorm: 'eac-rg11snorm',
  52798. // ASTC compressed formats usable if 'texture-compression-astc' is both
  52799. // supported by the device/user agent and enabled in requestDevice.
  52800. ASTC4x4Unorm: 'astc-4x4-unorm',
  52801. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  52802. ASTC5x4Unorm: 'astc-5x4-unorm',
  52803. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  52804. ASTC5x5Unorm: 'astc-5x5-unorm',
  52805. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  52806. ASTC6x5Unorm: 'astc-6x5-unorm',
  52807. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  52808. ASTC6x6Unorm: 'astc-6x6-unorm',
  52809. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  52810. ASTC8x5Unorm: 'astc-8x5-unorm',
  52811. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  52812. ASTC8x6Unorm: 'astc-8x6-unorm',
  52813. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  52814. ASTC8x8Unorm: 'astc-8x8-unorm',
  52815. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  52816. ASTC10x5Unorm: 'astc-10x5-unorm',
  52817. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  52818. ASTC10x6Unorm: 'astc-10x6-unorm',
  52819. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  52820. ASTC10x8Unorm: 'astc-10x8-unorm',
  52821. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  52822. ASTC10x10Unorm: 'astc-10x10-unorm',
  52823. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  52824. ASTC12x10Unorm: 'astc-12x10-unorm',
  52825. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  52826. ASTC12x12Unorm: 'astc-12x12-unorm',
  52827. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  52828. };
  52829. const GPUAddressMode = {
  52830. ClampToEdge: 'clamp-to-edge',
  52831. Repeat: 'repeat',
  52832. MirrorRepeat: 'mirror-repeat'
  52833. };
  52834. const GPUFilterMode = {
  52835. Linear: 'linear',
  52836. Nearest: 'nearest'
  52837. };
  52838. const GPUBlendFactor = {
  52839. Zero: 'zero',
  52840. One: 'one',
  52841. Src: 'src',
  52842. OneMinusSrc: 'one-minus-src',
  52843. SrcAlpha: 'src-alpha',
  52844. OneMinusSrcAlpha: 'one-minus-src-alpha',
  52845. Dst: 'dst',
  52846. OneMinusDst: 'one-minus-dst',
  52847. DstAlpha: 'dst-alpha',
  52848. OneMinusDstAlpha: 'one-minus-dst-alpha',
  52849. SrcAlphaSaturated: 'src-alpha-saturated',
  52850. Constant: 'constant',
  52851. OneMinusConstant: 'one-minus-constant'
  52852. };
  52853. const GPUBlendOperation = {
  52854. Add: 'add',
  52855. Subtract: 'subtract',
  52856. ReverseSubtract: 'reverse-subtract',
  52857. Min: 'min',
  52858. Max: 'max'
  52859. };
  52860. const GPUColorWriteFlags = {
  52861. None: 0,
  52862. All: 0xF
  52863. };
  52864. const GPUStencilOperation = {
  52865. Keep: 'keep',
  52866. Zero: 'zero',
  52867. Replace: 'replace',
  52868. Invert: 'invert',
  52869. IncrementClamp: 'increment-clamp',
  52870. DecrementClamp: 'decrement-clamp',
  52871. IncrementWrap: 'increment-wrap',
  52872. DecrementWrap: 'decrement-wrap'
  52873. };
  52874. const GPUBufferBindingType = {
  52875. Storage: 'storage',
  52876. ReadOnlyStorage: 'read-only-storage'
  52877. };
  52878. const GPUStorageTextureAccess = {
  52879. WriteOnly: 'write-only',
  52880. ReadOnly: 'read-only',
  52881. ReadWrite: 'read-write',
  52882. };
  52883. const GPUSamplerBindingType = {
  52884. NonFiltering: 'non-filtering',
  52885. Comparison: 'comparison'
  52886. };
  52887. const GPUTextureSampleType = {
  52888. Float: 'float',
  52889. UnfilterableFloat: 'unfilterable-float',
  52890. Depth: 'depth',
  52891. SInt: 'sint',
  52892. UInt: 'uint'
  52893. };
  52894. const GPUTextureDimension = {
  52895. TwoD: '2d',
  52896. ThreeD: '3d'
  52897. };
  52898. const GPUTextureViewDimension = {
  52899. TwoD: '2d',
  52900. TwoDArray: '2d-array',
  52901. Cube: 'cube',
  52902. ThreeD: '3d'
  52903. };
  52904. const GPUTextureAspect = {
  52905. All: 'all'};
  52906. const GPUInputStepMode = {
  52907. Vertex: 'vertex',
  52908. Instance: 'instance'
  52909. };
  52910. const GPUFeatureName = {
  52911. CoreFeaturesAndLimits: 'core-features-and-limits',
  52912. DepthClipControl: 'depth-clip-control',
  52913. Depth32FloatStencil8: 'depth32float-stencil8',
  52914. TextureCompressionBC: 'texture-compression-bc',
  52915. TextureCompressionBCSliced3D: 'texture-compression-bc-sliced-3d',
  52916. TextureCompressionETC2: 'texture-compression-etc2',
  52917. TextureCompressionASTC: 'texture-compression-astc',
  52918. TextureCompressionASTCSliced3D: 'texture-compression-astc-sliced-3d',
  52919. TimestampQuery: 'timestamp-query',
  52920. IndirectFirstInstance: 'indirect-first-instance',
  52921. ShaderF16: 'shader-f16',
  52922. RG11B10UFloat: 'rg11b10ufloat-renderable',
  52923. BGRA8UNormStorage: 'bgra8unorm-storage',
  52924. Float32Filterable: 'float32-filterable',
  52925. Float32Blendable: 'float32-blendable',
  52926. ClipDistances: 'clip-distances',
  52927. DualSourceBlending: 'dual-source-blending',
  52928. Subgroups: 'subgroups',
  52929. TextureFormatsTier1: 'texture-formats-tier1',
  52930. TextureFormatsTier2: 'texture-formats-tier2'
  52931. };
  52932. const GPUFeatureMap = {
  52933. 'texture-compression-s3tc': 'texture-compression-bc',
  52934. 'texture-compression-etc1': 'texture-compression-etc2'
  52935. };
  52936. /**
  52937. * A special form of sampler binding type.
  52938. * It's texture value is managed by a node object.
  52939. *
  52940. * @private
  52941. * @augments Sampler
  52942. */
  52943. class NodeSampler extends Sampler {
  52944. /**
  52945. * Constructs a new node-based sampler.
  52946. *
  52947. * @param {string} name - The samplers's name.
  52948. * @param {TextureNode} textureNode - The texture node.
  52949. * @param {UniformGroupNode} groupNode - The uniform group node.
  52950. */
  52951. constructor( name, textureNode, groupNode ) {
  52952. super( name, textureNode ? textureNode.value : null );
  52953. /**
  52954. * The texture node.
  52955. *
  52956. * @type {TextureNode}
  52957. */
  52958. this.textureNode = textureNode;
  52959. /**
  52960. * The uniform group node.
  52961. *
  52962. * @type {UniformGroupNode}
  52963. */
  52964. this.groupNode = groupNode;
  52965. }
  52966. /**
  52967. * Updates the texture value of this sampler.
  52968. *
  52969. * @return {boolean} Whether the sampler needs an update or not.
  52970. */
  52971. update() {
  52972. const { textureNode } = this;
  52973. if ( this.texture !== textureNode.value ) {
  52974. this.texture = textureNode.value;
  52975. return true;
  52976. }
  52977. return super.update();
  52978. }
  52979. }
  52980. /**
  52981. * Represents a storage buffer binding type.
  52982. *
  52983. * @private
  52984. * @augments Buffer
  52985. */
  52986. class StorageBuffer extends Buffer {
  52987. /**
  52988. * Constructs a new uniform buffer.
  52989. *
  52990. * @param {string} name - The buffer's name.
  52991. * @param {BufferAttribute} attribute - The buffer attribute.
  52992. */
  52993. constructor( name, attribute ) {
  52994. super( name, attribute ? attribute.array : null );
  52995. /**
  52996. * This flag can be used for type testing.
  52997. *
  52998. * @private
  52999. * @type {BufferAttribute}
  53000. */
  53001. this._attribute = attribute;
  53002. /**
  53003. * This flag can be used for type testing.
  53004. *
  53005. * @type {boolean}
  53006. * @readonly
  53007. * @default true
  53008. */
  53009. this.isStorageBuffer = true;
  53010. }
  53011. /**
  53012. * The storage buffer attribute.
  53013. *
  53014. * @type {BufferAttribute}
  53015. */
  53016. get attribute() {
  53017. return this._attribute;
  53018. }
  53019. }
  53020. let _id = 0;
  53021. /**
  53022. * A special form of storage buffer binding type.
  53023. * It's buffer value is managed by a node object.
  53024. *
  53025. * @private
  53026. * @augments StorageBuffer
  53027. */
  53028. class NodeStorageBuffer extends StorageBuffer {
  53029. /**
  53030. * Constructs a new node-based storage buffer.
  53031. *
  53032. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  53033. * @param {UniformGroupNode} groupNode - The uniform group node.
  53034. */
  53035. constructor( nodeUniform, groupNode ) {
  53036. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  53037. /**
  53038. * The node uniform.
  53039. *
  53040. * @type {StorageBufferNode}
  53041. */
  53042. this.nodeUniform = nodeUniform;
  53043. /**
  53044. * The access type.
  53045. *
  53046. * @type {string}
  53047. */
  53048. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  53049. /**
  53050. * The uniform group node.
  53051. *
  53052. * @type {UniformGroupNode}
  53053. */
  53054. this.groupNode = groupNode;
  53055. }
  53056. /**
  53057. * The storage buffer attribute node.
  53058. *
  53059. * @type {StorageBufferAttribute}
  53060. */
  53061. get attribute() {
  53062. return this.nodeUniform.value;
  53063. }
  53064. /**
  53065. * The storage buffer.
  53066. *
  53067. * @type {Float32Array}
  53068. */
  53069. get buffer() {
  53070. return this.nodeUniform.value.array;
  53071. }
  53072. }
  53073. const _commandList = [ null ];
  53074. /**
  53075. * A WebGPU backend utility module with common helpers.
  53076. *
  53077. * @private
  53078. */
  53079. class WebGPUUtils {
  53080. /**
  53081. * Constructs a new utility object.
  53082. *
  53083. * @param {WebGPUBackend} backend - The WebGPU backend.
  53084. */
  53085. constructor( backend ) {
  53086. /**
  53087. * A reference to the WebGPU backend.
  53088. *
  53089. * @type {WebGPUBackend}
  53090. */
  53091. this.backend = backend;
  53092. /**
  53093. * Caches the preferred canvas format.
  53094. *
  53095. * @private
  53096. * @type {?string}
  53097. * @default null
  53098. */
  53099. this._preferredCanvasFormat = null;
  53100. }
  53101. /**
  53102. * Returns the depth/stencil GPU format for the given render context.
  53103. *
  53104. * @param {RenderContext} renderContext - The render context.
  53105. * @return {string} The depth/stencil GPU texture format.
  53106. */
  53107. getCurrentDepthStencilFormat( renderContext ) {
  53108. let format;
  53109. if ( renderContext.depth ) {
  53110. if ( renderContext.depthTexture !== null ) {
  53111. format = this.getTextureFormatGPU( renderContext.depthTexture );
  53112. } else if ( renderContext.stencil ) {
  53113. if ( this.backend.renderer.reversedDepthBuffer === true ) {
  53114. format = GPUTextureFormat.Depth32FloatStencil8;
  53115. } else {
  53116. format = GPUTextureFormat.Depth24PlusStencil8;
  53117. }
  53118. } else {
  53119. if ( this.backend.renderer.reversedDepthBuffer === true ) {
  53120. format = GPUTextureFormat.Depth32Float;
  53121. } else {
  53122. format = GPUTextureFormat.Depth24Plus;
  53123. }
  53124. }
  53125. }
  53126. return format;
  53127. }
  53128. /**
  53129. * Returns the GPU format for the given texture.
  53130. *
  53131. * @param {Texture} texture - The texture.
  53132. * @return {string} The GPU texture format.
  53133. */
  53134. getTextureFormatGPU( texture ) {
  53135. return this.backend.get( texture ).format;
  53136. }
  53137. /**
  53138. * Returns an object that defines the multi-sampling state of the given texture.
  53139. *
  53140. * @param {Texture} texture - The texture.
  53141. * @return {Object} The multi-sampling state.
  53142. */
  53143. getTextureSampleData( texture ) {
  53144. let samples;
  53145. if ( texture.isFramebufferTexture ) {
  53146. samples = 1;
  53147. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  53148. const renderer = this.backend.renderer;
  53149. const renderTarget = renderer.getRenderTarget();
  53150. samples = renderTarget ? renderTarget.samples : renderer.currentSamples;
  53151. } else if ( texture.renderTarget ) {
  53152. samples = texture.renderTarget.samples;
  53153. }
  53154. samples = this.getSampleCount( samples || 1 );
  53155. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  53156. const primarySamples = isMSAA ? 1 : samples;
  53157. return { samples, primarySamples, isMSAA };
  53158. }
  53159. /**
  53160. * Returns the default color attachment's GPU format of the current render context.
  53161. *
  53162. * @param {RenderContext} renderContext - The render context.
  53163. * @return {string} The GPU texture format of the default color attachment.
  53164. */
  53165. getCurrentColorFormat( renderContext ) {
  53166. let format;
  53167. if ( renderContext.textures !== null ) {
  53168. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  53169. } else {
  53170. format = this.getPreferredCanvasFormat(); // default context format
  53171. }
  53172. return format;
  53173. }
  53174. /**
  53175. * Returns the GPU formats of all color attachments of the current render context.
  53176. *
  53177. * @param {RenderContext} renderContext - The render context.
  53178. * @return {Array<string>} The GPU texture formats of all color attachments.
  53179. */
  53180. getCurrentColorFormats( renderContext ) {
  53181. if ( renderContext.textures !== null ) {
  53182. return renderContext.textures.map( t => this.getTextureFormatGPU( t ) );
  53183. } else {
  53184. return [ this.getPreferredCanvasFormat() ]; // default context format
  53185. }
  53186. }
  53187. /**
  53188. * Returns the output color space of the current render context.
  53189. *
  53190. * @param {RenderContext} renderContext - The render context.
  53191. * @return {string} The output color space.
  53192. */
  53193. getCurrentColorSpace( renderContext ) {
  53194. if ( renderContext.textures !== null ) {
  53195. return renderContext.textures[ 0 ].colorSpace;
  53196. }
  53197. return this.backend.renderer.outputColorSpace;
  53198. }
  53199. /**
  53200. * Returns GPU primitive topology for the given object and material.
  53201. *
  53202. * @param {Object3D} object - The 3D object.
  53203. * @param {Material} material - The material.
  53204. * @return {string} The GPU primitive topology.
  53205. */
  53206. getPrimitiveTopology( object, material ) {
  53207. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  53208. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  53209. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  53210. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  53211. }
  53212. /**
  53213. * Returns a modified sample count from the given sample count value.
  53214. *
  53215. * That is required since WebGPU only supports either 1 or 4.
  53216. *
  53217. * @param {number} sampleCount - The input sample count.
  53218. * @return {number} The (potentially updated) output sample count.
  53219. */
  53220. getSampleCount( sampleCount ) {
  53221. return sampleCount >= 4 ? 4 : 1;
  53222. }
  53223. /**
  53224. * Returns the sample count of the given render context.
  53225. *
  53226. * @param {RenderContext} renderContext - The render context.
  53227. * @return {number} The sample count.
  53228. */
  53229. getSampleCountRenderContext( renderContext ) {
  53230. if ( renderContext.textures !== null ) {
  53231. return this.getSampleCount( renderContext.sampleCount );
  53232. }
  53233. return this.getSampleCount( this.backend.renderer.currentSamples );
  53234. }
  53235. /**
  53236. * Returns the preferred canvas format.
  53237. *
  53238. * There is a separate method for this so it's possible to
  53239. * honor edge cases for specific devices.
  53240. *
  53241. * @return {string} The GPU texture format of the canvas.
  53242. */
  53243. getPreferredCanvasFormat() {
  53244. const parameters = this.backend.parameters;
  53245. const bufferType = parameters.outputType;
  53246. if ( bufferType === undefined ) {
  53247. if ( this._preferredCanvasFormat === null ) {
  53248. this._preferredCanvasFormat = navigator.gpu.getPreferredCanvasFormat();
  53249. }
  53250. return this._preferredCanvasFormat;
  53251. } else if ( bufferType === UnsignedByteType ) {
  53252. return GPUTextureFormat.BGRA8Unorm;
  53253. } else if ( bufferType === HalfFloatType ) {
  53254. return GPUTextureFormat.RGBA16Float;
  53255. } else {
  53256. throw new Error( 'THREE.WebGPUUtils: Unsupported output buffer type.' );
  53257. }
  53258. }
  53259. }
  53260. /**
  53261. * Submits a single GPU command to the device queue using a shared, module-scoped
  53262. * array to avoid per-call array allocations.
  53263. *
  53264. * @private
  53265. * @param {GPUDevice} device - The GPU device.
  53266. * @param {GPUCommandBuffer} command - The command buffer to submit.
  53267. */
  53268. function submit( device, command ) {
  53269. _commandList[ 0 ] = command;
  53270. device.queue.submit( _commandList );
  53271. _commandList[ 0 ] = null;
  53272. }
  53273. /**
  53274. * Reusable descriptor for `GPUDevice.createBindGroup()`.
  53275. *
  53276. * @private
  53277. */
  53278. class GPUBindGroupDescriptor {
  53279. constructor() {
  53280. /**
  53281. * The label of the bind group.
  53282. *
  53283. * @type {string}
  53284. */
  53285. this.label = '';
  53286. /**
  53287. * The bind group layout the bind group conforms to.
  53288. *
  53289. * @type {?GPUBindGroupLayout}
  53290. * @default null
  53291. */
  53292. this.layout = null;
  53293. /**
  53294. * The bind group entries.
  53295. *
  53296. * @type {Array<Object>}
  53297. */
  53298. this.entries = [];
  53299. }
  53300. /**
  53301. * Resets the descriptor to its default state. The internal `entries` array
  53302. * is emptied without releasing its backing storage.
  53303. */
  53304. reset() {
  53305. this.label = '';
  53306. this.layout = null;
  53307. this.entries.length = 0;
  53308. }
  53309. }
  53310. /**
  53311. * Reusable descriptor for `GPUDevice.createBuffer()`.
  53312. *
  53313. * @private
  53314. */
  53315. class GPUBufferDescriptor {
  53316. constructor() {
  53317. /**
  53318. * The label of the buffer.
  53319. *
  53320. * @type {string}
  53321. */
  53322. this.label = '';
  53323. /**
  53324. * The size of the buffer in bytes.
  53325. *
  53326. * @type {number}
  53327. * @default 0
  53328. */
  53329. this.size = 0;
  53330. /**
  53331. * The allowed usages for the buffer.
  53332. *
  53333. * @type {number}
  53334. * @default 0
  53335. */
  53336. this.usage = 0;
  53337. /**
  53338. * Whether the buffer is in the mapped state at creation.
  53339. *
  53340. * @type {boolean}
  53341. * @default false
  53342. */
  53343. this.mappedAtCreation = false;
  53344. }
  53345. /**
  53346. * Resets the descriptor to its default state.
  53347. */
  53348. reset() {
  53349. this.label = '';
  53350. this.size = 0;
  53351. this.usage = 0;
  53352. this.mappedAtCreation = false;
  53353. }
  53354. }
  53355. /**
  53356. * Reusable descriptor for `GPUDevice.createCommandEncoder()`.
  53357. *
  53358. * @private
  53359. */
  53360. class GPUCommandEncoderDescriptor {
  53361. constructor() {
  53362. /**
  53363. * The label of the command encoder.
  53364. *
  53365. * @type {string}
  53366. */
  53367. this.label = '';
  53368. }
  53369. /**
  53370. * Resets the descriptor to its default state.
  53371. */
  53372. reset() {
  53373. this.label = '';
  53374. }
  53375. }
  53376. /**
  53377. * Reusable descriptor for `GPUDevice.createRenderBundleEncoder()`.
  53378. *
  53379. * @private
  53380. */
  53381. class GPURenderBundleEncoderDescriptor {
  53382. constructor() {
  53383. /**
  53384. * The label of the render bundle encoder.
  53385. *
  53386. * @type {string}
  53387. */
  53388. this.label = '';
  53389. /**
  53390. * The formats of the color attachments the bundle is compatible with.
  53391. *
  53392. * @type {?Array<?string>}
  53393. * @default null
  53394. */
  53395. this.colorFormats = null;
  53396. /**
  53397. * The format of the depth/stencil attachment the bundle is compatible with.
  53398. *
  53399. * @type {string|undefined}
  53400. */
  53401. this.depthStencilFormat = undefined;
  53402. /**
  53403. * The number of samples per pixel the bundle is compatible with.
  53404. *
  53405. * @type {number}
  53406. * @default 1
  53407. */
  53408. this.sampleCount = 1;
  53409. /**
  53410. * Whether the depth attachment is read-only.
  53411. *
  53412. * @type {boolean}
  53413. * @default false
  53414. */
  53415. this.depthReadOnly = false;
  53416. /**
  53417. * Whether the stencil attachment is read-only.
  53418. *
  53419. * @type {boolean}
  53420. * @default false
  53421. */
  53422. this.stencilReadOnly = false;
  53423. }
  53424. /**
  53425. * Resets the descriptor to its default state.
  53426. */
  53427. reset() {
  53428. this.label = '';
  53429. this.colorFormats = null;
  53430. this.depthStencilFormat = undefined;
  53431. this.sampleCount = 1;
  53432. this.depthReadOnly = false;
  53433. this.stencilReadOnly = false;
  53434. }
  53435. }
  53436. /**
  53437. * Reusable descriptor for `GPURenderPassColorAttachment`, the type of each
  53438. * entry in `GPURenderPassDescriptor.colorAttachments`.
  53439. *
  53440. * @private
  53441. */
  53442. class GPURenderPassColorAttachment {
  53443. constructor() {
  53444. /**
  53445. * The texture view the pass renders into.
  53446. *
  53447. * @type {?GPUTextureView}
  53448. * @default null
  53449. */
  53450. this.view = null;
  53451. /**
  53452. * The depth slice the pass renders into.
  53453. *
  53454. * @type {number|undefined}
  53455. */
  53456. this.depthSlice = undefined;
  53457. /**
  53458. * The texture view that receives the resolved output of multisampled rendering.
  53459. *
  53460. * @type {?GPUTextureView|undefined}
  53461. */
  53462. this.resolveTarget = undefined;
  53463. /**
  53464. * The clear value used when `loadOp` is `'clear'`.
  53465. *
  53466. * @type {Object|undefined}
  53467. */
  53468. this.clearValue = undefined;
  53469. /**
  53470. * The load operation performed at the start of the pass.
  53471. *
  53472. * @type {string|undefined}
  53473. */
  53474. this.loadOp = undefined;
  53475. /**
  53476. * The store operation performed at the end of the pass.
  53477. *
  53478. * @type {string|undefined}
  53479. */
  53480. this.storeOp = undefined;
  53481. }
  53482. /**
  53483. * Resets the descriptor to its default state.
  53484. */
  53485. reset() {
  53486. this.view = null;
  53487. this.depthSlice = undefined;
  53488. this.resolveTarget = undefined;
  53489. this.clearValue = undefined;
  53490. this.loadOp = undefined;
  53491. this.storeOp = undefined;
  53492. }
  53493. }
  53494. /**
  53495. * Reusable descriptor for `GPUCommandEncoder.beginRenderPass()`.
  53496. *
  53497. * @private
  53498. */
  53499. class GPURenderPassDescriptor {
  53500. constructor() {
  53501. /**
  53502. * The label of the render pass.
  53503. *
  53504. * @type {string}
  53505. */
  53506. this.label = '';
  53507. /**
  53508. * The color attachments of the render pass.
  53509. *
  53510. * @type {Array<?Object>}
  53511. */
  53512. this.colorAttachments = [];
  53513. /**
  53514. * The depth-stencil attachment of the render pass.
  53515. *
  53516. * @type {Object|undefined}
  53517. */
  53518. this.depthStencilAttachment = undefined;
  53519. /**
  53520. * The query set used for occlusion queries during the pass.
  53521. *
  53522. * @type {?GPUQuerySet|undefined}
  53523. */
  53524. this.occlusionQuerySet = undefined;
  53525. /**
  53526. * Defines which timestamp values are written and where.
  53527. *
  53528. * @type {Object|undefined}
  53529. */
  53530. this.timestampWrites = undefined;
  53531. /**
  53532. * The maximum number of draw calls that can be issued during the pass.
  53533. *
  53534. * @type {number}
  53535. * @default 50000000
  53536. */
  53537. this.maxDrawCount = 50000000;
  53538. }
  53539. /**
  53540. * Resets the descriptor to its default state. The internal `colorAttachments`
  53541. * array is emptied without releasing its backing storage.
  53542. */
  53543. reset() {
  53544. this.label = '';
  53545. this.colorAttachments.length = 0;
  53546. this.depthStencilAttachment = undefined;
  53547. this.occlusionQuerySet = undefined;
  53548. this.timestampWrites = undefined;
  53549. this.maxDrawCount = 50000000;
  53550. }
  53551. }
  53552. /**
  53553. * Reusable descriptor for `GPUDevice.createRenderPipeline()` and
  53554. * `createRenderPipelineAsync()`.
  53555. *
  53556. * @private
  53557. */
  53558. class GPURenderPipelineDescriptor {
  53559. constructor() {
  53560. /**
  53561. * The label of the render pipeline.
  53562. *
  53563. * @type {string}
  53564. */
  53565. this.label = '';
  53566. /**
  53567. * The pipeline layout the pipeline conforms to, or `'auto'`.
  53568. *
  53569. * @type {?GPUPipelineLayout|string}
  53570. * @default null
  53571. */
  53572. this.layout = null;
  53573. /**
  53574. * The programmable vertex stage.
  53575. *
  53576. * @type {?Object}
  53577. * @default null
  53578. */
  53579. this.vertex = null;
  53580. /**
  53581. * The primitive-assembly state.
  53582. *
  53583. * @type {Object}
  53584. */
  53585. this.primitive = {};
  53586. /**
  53587. * The depth/stencil state, omitted when the pipeline has no depth or stencil aspect.
  53588. *
  53589. * @type {Object|undefined}
  53590. */
  53591. this.depthStencil = undefined;
  53592. /**
  53593. * The multisample state.
  53594. *
  53595. * @type {GPUMultisampleState}
  53596. */
  53597. this.multisample = new GPUMultisampleState();
  53598. /**
  53599. * The programmable fragment stage. Omitted for vertex-only pipelines.
  53600. *
  53601. * @type {?Object}
  53602. * @default null
  53603. */
  53604. this.fragment = null;
  53605. }
  53606. /**
  53607. * Resets the descriptor to its default state.
  53608. */
  53609. reset() {
  53610. this.label = '';
  53611. this.layout = null;
  53612. this.vertex = null;
  53613. this.primitive = {};
  53614. this.depthStencil = undefined;
  53615. this.multisample.reset();
  53616. this.fragment = null;
  53617. }
  53618. }
  53619. /**
  53620. * Reusable nested state for `GPURenderPipelineDescriptor.multisample`.
  53621. *
  53622. * @private
  53623. */
  53624. class GPUMultisampleState {
  53625. constructor() {
  53626. /**
  53627. * The number of samples per pixel.
  53628. *
  53629. * @type {number}
  53630. * @default 1
  53631. */
  53632. this.count = 1;
  53633. /**
  53634. * A bitmask determining which samples are written to.
  53635. *
  53636. * @type {number}
  53637. * @default 0xFFFFFFFF
  53638. */
  53639. this.mask = 0xFFFFFFFF;
  53640. /**
  53641. * Whether a fragment's alpha channel is used to generate a sample coverage mask.
  53642. *
  53643. * @type {boolean}
  53644. * @default false
  53645. */
  53646. this.alphaToCoverageEnabled = false;
  53647. }
  53648. /**
  53649. * Resets the state to its default values.
  53650. */
  53651. reset() {
  53652. this.count = 1;
  53653. this.mask = 0xFFFFFFFF;
  53654. this.alphaToCoverageEnabled = false;
  53655. }
  53656. }
  53657. /**
  53658. * Reusable descriptor for `GPUDevice.createShaderModule()`.
  53659. *
  53660. * @private
  53661. */
  53662. class GPUShaderModuleDescriptor {
  53663. constructor() {
  53664. /**
  53665. * The label of the shader module.
  53666. *
  53667. * @type {string}
  53668. */
  53669. this.label = '';
  53670. /**
  53671. * The WGSL source code of the shader module.
  53672. *
  53673. * @type {string}
  53674. */
  53675. this.code = '';
  53676. /**
  53677. * Compilation hints that may help the implementation produce optimized code.
  53678. *
  53679. * @type {Array<Object>}
  53680. */
  53681. this.compilationHints = [];
  53682. }
  53683. /**
  53684. * Resets the descriptor to its default state.
  53685. */
  53686. reset() {
  53687. this.label = '';
  53688. this.code = '';
  53689. this.compilationHints.length = 0;
  53690. }
  53691. }
  53692. /**
  53693. * Reusable descriptor for `GPUDevice.createTexture()`.
  53694. *
  53695. * @private
  53696. */
  53697. class GPUTextureDescriptor {
  53698. constructor() {
  53699. /**
  53700. * The label of the texture.
  53701. *
  53702. * @type {string}
  53703. */
  53704. this.label = '';
  53705. /**
  53706. * The size of the texture.
  53707. *
  53708. * @type {{width: number, height: number, depthOrArrayLayers: number}}
  53709. */
  53710. this.size = { width: 0, height: 1, depthOrArrayLayers: 1 };
  53711. /**
  53712. * The number of mip levels the texture will contain.
  53713. *
  53714. * @type {number}
  53715. * @default 1
  53716. */
  53717. this.mipLevelCount = 1;
  53718. /**
  53719. * The sample count of the texture.
  53720. *
  53721. * @type {number}
  53722. * @default 1
  53723. */
  53724. this.sampleCount = 1;
  53725. /**
  53726. * The dimension of the set of texel coordinates.
  53727. *
  53728. * @type {string}
  53729. * @default '2d'
  53730. */
  53731. this.dimension = '2d';
  53732. /**
  53733. * The format of the texture.
  53734. *
  53735. * @type {string|undefined}
  53736. */
  53737. this.format = undefined;
  53738. /**
  53739. * The allowed usages for the texture.
  53740. *
  53741. * @type {number|undefined}
  53742. */
  53743. this.usage = undefined;
  53744. /**
  53745. * The formats that views of this texture may use.
  53746. *
  53747. * @type {Array<string>}
  53748. */
  53749. this.viewFormats = [];
  53750. /**
  53751. * The view dimension to use when binding the texture (compatibility mode).
  53752. *
  53753. * @type {string|undefined}
  53754. */
  53755. this.textureBindingViewDimension = undefined;
  53756. }
  53757. /**
  53758. * Resets the descriptor to its default state.
  53759. */
  53760. reset() {
  53761. this.label = '';
  53762. this.size.width = 0;
  53763. this.size.height = 1;
  53764. this.size.depthOrArrayLayers = 1;
  53765. this.mipLevelCount = 1;
  53766. this.sampleCount = 1;
  53767. this.dimension = '2d';
  53768. this.format = undefined;
  53769. this.usage = undefined;
  53770. this.viewFormats.length = 0;
  53771. this.textureBindingViewDimension = undefined;
  53772. }
  53773. }
  53774. /**
  53775. * Reusable descriptor for `GPUTexture.createView()`.
  53776. *
  53777. * @private
  53778. */
  53779. class GPUTextureViewDescriptor {
  53780. constructor() {
  53781. /**
  53782. * The label of the texture view.
  53783. *
  53784. * @type {string}
  53785. */
  53786. this.label = '';
  53787. /**
  53788. * The format of the texture view.
  53789. *
  53790. * @type {string|undefined}
  53791. */
  53792. this.format = undefined;
  53793. /**
  53794. * The dimension of the texture view.
  53795. *
  53796. * @type {string|undefined}
  53797. */
  53798. this.dimension = undefined;
  53799. /**
  53800. * The allowed usages for the texture view.
  53801. *
  53802. * @type {number}
  53803. * @default 0
  53804. */
  53805. this.usage = 0;
  53806. /**
  53807. * Which aspect of the texture is referenced.
  53808. *
  53809. * @type {string}
  53810. * @default 'all'
  53811. */
  53812. this.aspect = 'all';
  53813. /**
  53814. * The first mip level accessible to the texture view.
  53815. *
  53816. * @type {number}
  53817. * @default 0
  53818. */
  53819. this.baseMipLevel = 0;
  53820. /**
  53821. * The number of mip levels accessible to the texture view.
  53822. *
  53823. * @type {number|undefined}
  53824. */
  53825. this.mipLevelCount = undefined;
  53826. /**
  53827. * The first array layer accessible to the texture view.
  53828. *
  53829. * @type {number}
  53830. * @default 0
  53831. */
  53832. this.baseArrayLayer = 0;
  53833. /**
  53834. * The number of array layers accessible to the texture view.
  53835. *
  53836. * @type {number|undefined}
  53837. */
  53838. this.arrayLayerCount = undefined;
  53839. /**
  53840. * The component swizzle to apply when sampling the texture view.
  53841. * Requires the `'texture-component-swizzle'` feature; ignored otherwise.
  53842. *
  53843. * @type {string}
  53844. * @default 'rgba'
  53845. */
  53846. this.swizzle = 'rgba';
  53847. }
  53848. /**
  53849. * Resets the descriptor to its default state.
  53850. */
  53851. reset() {
  53852. this.label = '';
  53853. this.format = undefined;
  53854. this.dimension = undefined;
  53855. this.usage = 0;
  53856. this.aspect = 'all';
  53857. this.baseMipLevel = 0;
  53858. this.mipLevelCount = undefined;
  53859. this.baseArrayLayer = 0;
  53860. this.arrayLayerCount = undefined;
  53861. this.swizzle = 'rgba';
  53862. }
  53863. }
  53864. const _bindGroupDescriptor$1 = new GPUBindGroupDescriptor();
  53865. const _bufferDescriptor$5 = new GPUBufferDescriptor();
  53866. const _commandEncoderDescriptor$4 = new GPUCommandEncoderDescriptor();
  53867. const _renderBundleEncoderDescriptor$1 = new GPURenderBundleEncoderDescriptor();
  53868. const _renderPassDescriptor = new GPURenderPassDescriptor();
  53869. const _renderPipelineDescriptor$1 = new GPURenderPipelineDescriptor();
  53870. const _colorAttachment = new GPURenderPassColorAttachment();
  53871. const _shaderModuleDescriptor$1 = new GPUShaderModuleDescriptor();
  53872. const _textureDescriptor$1 = new GPUTextureDescriptor();
  53873. const _viewDescriptor$2 = new GPUTextureViewDescriptor();
  53874. /**
  53875. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  53876. *
  53877. * @private
  53878. */
  53879. class WebGPUTexturePassUtils extends DataMap {
  53880. /**
  53881. * Constructs a new utility object.
  53882. *
  53883. * @param {GPUDevice} device - The WebGPU device.
  53884. */
  53885. constructor( device ) {
  53886. super();
  53887. /**
  53888. * The WebGPU device.
  53889. *
  53890. * @type {GPUDevice}
  53891. */
  53892. this.device = device;
  53893. const mipmapSource = `
  53894. struct VarysStruct {
  53895. @builtin( position ) Position: vec4f,
  53896. @location( 0 ) vTex : vec2f,
  53897. @location( 1 ) @interpolate(flat, either) vBaseArrayLayer: u32,
  53898. };
  53899. @group( 0 ) @binding ( 2 )
  53900. var<uniform> flipY: u32;
  53901. @vertex
  53902. fn mainVS(
  53903. @builtin( vertex_index ) vertexIndex : u32,
  53904. @builtin( instance_index ) instanceIndex : u32 ) -> VarysStruct {
  53905. var Varys : VarysStruct;
  53906. var pos = array(
  53907. vec2f( -1, -1 ),
  53908. vec2f( -1, 3 ),
  53909. vec2f( 3, -1 ),
  53910. );
  53911. let p = pos[ vertexIndex ];
  53912. let mult = select( vec2f( 0.5, -0.5 ), vec2f( 0.5, 0.5 ), flipY != 0 );
  53913. Varys.vTex = p * mult + vec2f( 0.5 );
  53914. Varys.Position = vec4f( p, 0, 1 );
  53915. Varys.vBaseArrayLayer = instanceIndex;
  53916. return Varys;
  53917. }
  53918. @group( 0 ) @binding( 0 )
  53919. var imgSampler : sampler;
  53920. @group( 0 ) @binding( 1 )
  53921. var img2d : texture_2d<f32>;
  53922. @fragment
  53923. fn main_2d( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {
  53924. return textureSample( img2d, imgSampler, Varys.vTex );
  53925. }
  53926. @group( 0 ) @binding( 1 )
  53927. var img2dArray : texture_2d_array<f32>;
  53928. @fragment
  53929. fn main_2d_array( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {
  53930. return textureSample( img2dArray, imgSampler, Varys.vTex, Varys.vBaseArrayLayer );
  53931. }
  53932. const faceMat = array(
  53933. mat3x3f( 0, 0, -2, 0, -2, 0, 1, 1, 1 ), // pos-x
  53934. mat3x3f( 0, 0, 2, 0, -2, 0, -1, 1, -1 ), // neg-x
  53935. mat3x3f( 2, 0, 0, 0, 0, 2, -1, 1, -1 ), // pos-y
  53936. mat3x3f( 2, 0, 0, 0, 0, -2, -1, -1, 1 ), // neg-y
  53937. mat3x3f( 2, 0, 0, 0, -2, 0, -1, 1, 1 ), // pos-z
  53938. mat3x3f( -2, 0, 0, 0, -2, 0, 1, 1, -1 ), // neg-z
  53939. );
  53940. @group( 0 ) @binding( 1 )
  53941. var imgCube : texture_cube<f32>;
  53942. @fragment
  53943. fn main_cube( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {
  53944. return textureSample( imgCube, imgSampler, faceMat[ Varys.vBaseArrayLayer ] * vec3f( fract( Varys.vTex ), 1 ) );
  53945. }
  53946. `;
  53947. /**
  53948. * The mipmap GPU sampler.
  53949. *
  53950. * @type {GPUSampler}
  53951. */
  53952. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  53953. /**
  53954. * The flipY GPU sampler.
  53955. *
  53956. * @type {GPUSampler}
  53957. */
  53958. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  53959. /**
  53960. * flip uniform buffer
  53961. * @type {GPUBuffer}
  53962. */
  53963. _bufferDescriptor$5.size = 4;
  53964. _bufferDescriptor$5.usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  53965. this.flipUniformBuffer = device.createBuffer( _bufferDescriptor$5 );
  53966. _bufferDescriptor$5.reset();
  53967. device.queue.writeBuffer( this.flipUniformBuffer, 0, new Uint32Array( [ 1 ] ) );
  53968. /**
  53969. * no flip uniform buffer
  53970. * @type {GPUBuffer}
  53971. */
  53972. _bufferDescriptor$5.size = 4;
  53973. _bufferDescriptor$5.usage = GPUBufferUsage.UNIFORM;
  53974. this.noFlipUniformBuffer = device.createBuffer( _bufferDescriptor$5 );
  53975. _bufferDescriptor$5.reset();
  53976. /**
  53977. * A cache for GPU render pipelines used for copy/transfer passes.
  53978. * Every texture format and textureBindingViewDimension combo requires a unique pipeline.
  53979. *
  53980. * @type {Object<string,GPURenderPipeline>}
  53981. */
  53982. this.transferPipelines = {};
  53983. /**
  53984. * The mipmap shader module.
  53985. *
  53986. * @type {GPUShaderModule}
  53987. */
  53988. _shaderModuleDescriptor$1.label = 'mipmap';
  53989. _shaderModuleDescriptor$1.code = mipmapSource;
  53990. this.mipmapShaderModule = device.createShaderModule( _shaderModuleDescriptor$1 );
  53991. _shaderModuleDescriptor$1.reset();
  53992. }
  53993. /**
  53994. * Returns a render pipeline for the internal copy render pass. The pass
  53995. * requires a unique render pipeline for each texture format.
  53996. *
  53997. * @param {string} format - The GPU texture format
  53998. * @param {string?} textureBindingViewDimension - The GPU texture binding view dimension
  53999. * @return {GPURenderPipeline} The GPU render pipeline.
  54000. */
  54001. getTransferPipeline( format, textureBindingViewDimension ) {
  54002. textureBindingViewDimension = textureBindingViewDimension || '2d-array';
  54003. const key = `${ format }-${ textureBindingViewDimension }`;
  54004. let pipeline = this.transferPipelines[ key ];
  54005. if ( pipeline === undefined ) {
  54006. _renderPipelineDescriptor$1.label = `mipmap-${ format }-${ textureBindingViewDimension }`;
  54007. _renderPipelineDescriptor$1.vertex = { module: this.mipmapShaderModule };
  54008. _renderPipelineDescriptor$1.fragment = {
  54009. module: this.mipmapShaderModule,
  54010. entryPoint: `main_${ textureBindingViewDimension.replace( '-', '_' ) }`,
  54011. targets: [ { format } ]
  54012. };
  54013. _renderPipelineDescriptor$1.layout = 'auto';
  54014. pipeline = this.device.createRenderPipeline( _renderPipelineDescriptor$1 );
  54015. _renderPipelineDescriptor$1.reset();
  54016. this.transferPipelines[ key ] = pipeline;
  54017. }
  54018. return pipeline;
  54019. }
  54020. /**
  54021. * Flip the contents of the given GPU texture along its vertical axis.
  54022. *
  54023. * @param {GPUTexture} textureGPU - The GPU texture object.
  54024. * @param {Object} textureGPUDescriptor - The texture descriptor.
  54025. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  54026. */
  54027. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  54028. const format = textureGPUDescriptor.format;
  54029. const { width, height } = textureGPUDescriptor.size;
  54030. _textureDescriptor$1.size.width = width;
  54031. _textureDescriptor$1.size.height = height;
  54032. _textureDescriptor$1.format = format;
  54033. _textureDescriptor$1.usage = GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING;
  54034. const tempTexture = this.device.createTexture( _textureDescriptor$1 );
  54035. _textureDescriptor$1.reset();
  54036. const copyTransferPipeline = this.getTransferPipeline( format, textureGPU.textureBindingViewDimension );
  54037. const flipTransferPipeline = this.getTransferPipeline( format, tempTexture.textureBindingViewDimension );
  54038. const commandEncoder = this.device.createCommandEncoder( _commandEncoderDescriptor$4 );
  54039. const pass = ( pipeline, sourceTexture, sourceArrayLayer, destinationTexture, destinationArrayLayer, flipY ) => {
  54040. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  54041. _viewDescriptor$2.dimension = sourceTexture.textureBindingViewDimension || '2d-array';
  54042. _viewDescriptor$2.mipLevelCount = 1;
  54043. const sourceView = sourceTexture.createView( _viewDescriptor$2 );
  54044. _viewDescriptor$2.reset();
  54045. _bindGroupDescriptor$1.layout = bindGroupLayout;
  54046. _bindGroupDescriptor$1.entries.push( {
  54047. binding: 0,
  54048. resource: this.flipYSampler
  54049. }, {
  54050. binding: 1,
  54051. resource: sourceView,
  54052. }, {
  54053. binding: 2,
  54054. resource: { buffer: flipY ? this.flipUniformBuffer : this.noFlipUniformBuffer }
  54055. } );
  54056. const bindGroup = this.device.createBindGroup( _bindGroupDescriptor$1 );
  54057. _bindGroupDescriptor$1.reset();
  54058. _viewDescriptor$2.dimension = '2d';
  54059. _viewDescriptor$2.mipLevelCount = 1;
  54060. _viewDescriptor$2.baseArrayLayer = destinationArrayLayer;
  54061. _viewDescriptor$2.arrayLayerCount = 1;
  54062. const destinationView = destinationTexture.createView( _viewDescriptor$2 );
  54063. _viewDescriptor$2.reset();
  54064. _colorAttachment.view = destinationView;
  54065. _colorAttachment.loadOp = GPULoadOp.Clear;
  54066. _colorAttachment.storeOp = GPUStoreOp.Store;
  54067. _renderPassDescriptor.colorAttachments.push( _colorAttachment );
  54068. const passEncoder = commandEncoder.beginRenderPass( _renderPassDescriptor );
  54069. _renderPassDescriptor.reset();
  54070. _colorAttachment.reset();
  54071. passEncoder.setPipeline( pipeline );
  54072. passEncoder.setBindGroup( 0, bindGroup );
  54073. passEncoder.draw( 3, 1, 0, sourceArrayLayer );
  54074. passEncoder.end();
  54075. };
  54076. pass( copyTransferPipeline, textureGPU, baseArrayLayer, tempTexture, 0, false );
  54077. pass( flipTransferPipeline, tempTexture, 0, textureGPU, baseArrayLayer, true );
  54078. submit( this.device, commandEncoder.finish() );
  54079. tempTexture.destroy();
  54080. }
  54081. /**
  54082. * Generates mipmaps for the given GPU texture.
  54083. *
  54084. * @param {GPUTexture} textureGPU - The GPU texture object.
  54085. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  54086. */
  54087. generateMipmaps( textureGPU, encoder = null ) {
  54088. const textureData = this.get( textureGPU );
  54089. const passes = textureData.layers || this._mipmapCreateBundles( textureGPU );
  54090. let commandEncoder = encoder;
  54091. if ( commandEncoder === null ) {
  54092. _commandEncoderDescriptor$4.label = 'mipmapEncoder';
  54093. commandEncoder = this.device.createCommandEncoder( _commandEncoderDescriptor$4 );
  54094. _commandEncoderDescriptor$4.reset();
  54095. }
  54096. this._mipmapRunBundles( commandEncoder, passes );
  54097. if ( encoder === null ) submit( this.device, commandEncoder.finish() );
  54098. textureData.layers = passes;
  54099. }
  54100. /**
  54101. * Since multiple copy render passes are required to generate mipmaps, the passes
  54102. * are managed as render bundles to improve performance.
  54103. *
  54104. * @param {GPUTexture} textureGPU - The GPU texture object.
  54105. * @return {Array<Object>} An array of render bundles.
  54106. */
  54107. _mipmapCreateBundles( textureGPU ) {
  54108. const textureBindingViewDimension = textureGPU.textureBindingViewDimension || '2d-array';
  54109. const pipeline = this.getTransferPipeline( textureGPU.format, textureBindingViewDimension );
  54110. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  54111. const passes = [];
  54112. for ( let baseMipLevel = 1; baseMipLevel < textureGPU.mipLevelCount; baseMipLevel ++ ) {
  54113. for ( let baseArrayLayer = 0; baseArrayLayer < textureGPU.depthOrArrayLayers; baseArrayLayer ++ ) {
  54114. _viewDescriptor$2.dimension = textureBindingViewDimension;
  54115. _viewDescriptor$2.baseMipLevel = baseMipLevel - 1;
  54116. _viewDescriptor$2.mipLevelCount = 1;
  54117. const sourceView = textureGPU.createView( _viewDescriptor$2 );
  54118. _viewDescriptor$2.reset();
  54119. _bindGroupDescriptor$1.layout = bindGroupLayout;
  54120. _bindGroupDescriptor$1.entries.push( {
  54121. binding: 0,
  54122. resource: this.mipmapSampler
  54123. }, {
  54124. binding: 1,
  54125. resource: sourceView,
  54126. }, {
  54127. binding: 2,
  54128. resource: { buffer: this.noFlipUniformBuffer }
  54129. } );
  54130. const bindGroup = this.device.createBindGroup( _bindGroupDescriptor$1 );
  54131. _bindGroupDescriptor$1.reset();
  54132. _viewDescriptor$2.dimension = '2d';
  54133. _viewDescriptor$2.baseMipLevel = baseMipLevel;
  54134. _viewDescriptor$2.mipLevelCount = 1;
  54135. _viewDescriptor$2.baseArrayLayer = baseArrayLayer;
  54136. _viewDescriptor$2.arrayLayerCount = 1;
  54137. const destinationView = textureGPU.createView( _viewDescriptor$2 );
  54138. _viewDescriptor$2.reset();
  54139. const passColorAttachment = new GPURenderPassColorAttachment();
  54140. passColorAttachment.view = destinationView;
  54141. passColorAttachment.loadOp = GPULoadOp.Clear;
  54142. passColorAttachment.storeOp = GPUStoreOp.Store;
  54143. const passDescriptor = new GPURenderPassDescriptor();
  54144. passDescriptor.colorAttachments.push( passColorAttachment );
  54145. _renderBundleEncoderDescriptor$1.colorFormats = [ textureGPU.format ];
  54146. const passEncoder = this.device.createRenderBundleEncoder( _renderBundleEncoderDescriptor$1 );
  54147. _renderBundleEncoderDescriptor$1.reset();
  54148. passEncoder.setPipeline( pipeline );
  54149. passEncoder.setBindGroup( 0, bindGroup );
  54150. passEncoder.draw( 3, 1, 0, baseArrayLayer );
  54151. passes.push( {
  54152. renderBundles: [ passEncoder.finish() ],
  54153. passDescriptor
  54154. } );
  54155. }
  54156. }
  54157. return passes;
  54158. }
  54159. /**
  54160. * Executes the render bundles.
  54161. *
  54162. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  54163. * @param {Array<Object>} passes - An array of render bundles.
  54164. */
  54165. _mipmapRunBundles( commandEncoder, passes ) {
  54166. const levels = passes.length;
  54167. for ( let i = 0; i < levels; i ++ ) {
  54168. const pass = passes[ i ];
  54169. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  54170. passEncoder.executeBundles( pass.renderBundles );
  54171. passEncoder.end();
  54172. }
  54173. }
  54174. }
  54175. /**
  54176. * Reusable descriptor for `GPUDevice.createSampler()`.
  54177. *
  54178. * @private
  54179. */
  54180. class GPUSamplerDescriptor {
  54181. constructor() {
  54182. /**
  54183. * The label of the sampler.
  54184. *
  54185. * @type {string}
  54186. */
  54187. this.label = '';
  54188. /**
  54189. * The address mode for the sampler's U coordinate.
  54190. *
  54191. * @type {string}
  54192. * @default 'clamp-to-edge'
  54193. */
  54194. this.addressModeU = 'clamp-to-edge';
  54195. /**
  54196. * The address mode for the sampler's V coordinate.
  54197. *
  54198. * @type {string}
  54199. * @default 'clamp-to-edge'
  54200. */
  54201. this.addressModeV = 'clamp-to-edge';
  54202. /**
  54203. * The address mode for the sampler's W coordinate.
  54204. *
  54205. * @type {string}
  54206. * @default 'clamp-to-edge'
  54207. */
  54208. this.addressModeW = 'clamp-to-edge';
  54209. /**
  54210. * The magnification filter mode.
  54211. *
  54212. * @type {string}
  54213. * @default 'nearest'
  54214. */
  54215. this.magFilter = 'nearest';
  54216. /**
  54217. * The minification filter mode.
  54218. *
  54219. * @type {string}
  54220. * @default 'nearest'
  54221. */
  54222. this.minFilter = 'nearest';
  54223. /**
  54224. * The mipmap filter mode.
  54225. *
  54226. * @type {string}
  54227. * @default 'nearest'
  54228. */
  54229. this.mipmapFilter = 'nearest';
  54230. /**
  54231. * The minimum level of detail used to sample.
  54232. *
  54233. * @type {number}
  54234. * @default 0
  54235. */
  54236. this.lodMinClamp = 0;
  54237. /**
  54238. * The maximum level of detail used to sample.
  54239. *
  54240. * @type {number}
  54241. * @default 32
  54242. */
  54243. this.lodMaxClamp = 32;
  54244. /**
  54245. * The compare function used by the sampler.
  54246. *
  54247. * @type {string|undefined}
  54248. */
  54249. this.compare = undefined;
  54250. /**
  54251. * The maximum allowed anisotropic filtering.
  54252. *
  54253. * @type {number}
  54254. * @default 1
  54255. */
  54256. this.maxAnisotropy = 1;
  54257. }
  54258. /**
  54259. * Resets the descriptor to its default state.
  54260. */
  54261. reset() {
  54262. this.label = '';
  54263. this.addressModeU = 'clamp-to-edge';
  54264. this.addressModeV = 'clamp-to-edge';
  54265. this.addressModeW = 'clamp-to-edge';
  54266. this.magFilter = 'nearest';
  54267. this.minFilter = 'nearest';
  54268. this.mipmapFilter = 'nearest';
  54269. this.lodMinClamp = 0;
  54270. this.lodMaxClamp = 32;
  54271. this.compare = undefined;
  54272. this.maxAnisotropy = 1;
  54273. }
  54274. }
  54275. /**
  54276. * Reusable descriptor for `GPUTexelCopyTextureInfo`, the texture side of
  54277. * `GPUCommandEncoder.copyTextureToTexture()`, `copyTextureToBuffer()` and
  54278. * `GPUQueue.writeTexture()`.
  54279. *
  54280. * @private
  54281. */
  54282. class GPUTexelCopyTextureInfo {
  54283. constructor() {
  54284. /**
  54285. * The target texture.
  54286. *
  54287. * @type {?GPUTexture}
  54288. * @default null
  54289. */
  54290. this.texture = null;
  54291. /**
  54292. * The mipmap level of the texture.
  54293. *
  54294. * @type {number}
  54295. * @default 0
  54296. */
  54297. this.mipLevel = 0;
  54298. /**
  54299. * The origin offset within the texture.
  54300. *
  54301. * @type {{x: number, y: number, z: number}}
  54302. */
  54303. this.origin = { x: 0, y: 0, z: 0 };
  54304. /**
  54305. * Which aspect of the texture is referenced.
  54306. *
  54307. * @type {string}
  54308. * @default 'all'
  54309. */
  54310. this.aspect = 'all';
  54311. }
  54312. /**
  54313. * Resets the descriptor to its default state.
  54314. */
  54315. reset() {
  54316. this.texture = null;
  54317. this.mipLevel = 0;
  54318. this.origin.x = 0;
  54319. this.origin.y = 0;
  54320. this.origin.z = 0;
  54321. this.aspect = 'all';
  54322. }
  54323. }
  54324. /**
  54325. * Reusable descriptor for `GPUTexelCopyBufferInfo`, the buffer side of
  54326. * `GPUCommandEncoder.copyTextureToBuffer()` and `copyBufferToTexture()`.
  54327. *
  54328. * @private
  54329. */
  54330. class GPUTexelCopyBufferInfo {
  54331. constructor() {
  54332. /**
  54333. * The target buffer.
  54334. *
  54335. * @type {?GPUBuffer}
  54336. * @default null
  54337. */
  54338. this.buffer = null;
  54339. /**
  54340. * The byte offset within the buffer where the texel data begins.
  54341. *
  54342. * @type {number}
  54343. * @default 0
  54344. */
  54345. this.offset = 0;
  54346. /**
  54347. * The stride, in bytes, between rows of texel blocks.
  54348. *
  54349. * @type {number|undefined}
  54350. */
  54351. this.bytesPerRow = undefined;
  54352. /**
  54353. * The number of texel block rows per single image of the texture.
  54354. *
  54355. * @type {number|undefined}
  54356. */
  54357. this.rowsPerImage = undefined;
  54358. }
  54359. /**
  54360. * Resets the descriptor to its default state.
  54361. */
  54362. reset() {
  54363. this.buffer = null;
  54364. this.offset = 0;
  54365. this.bytesPerRow = undefined;
  54366. this.rowsPerImage = undefined;
  54367. }
  54368. }
  54369. /**
  54370. * Reusable descriptor for `GPUTexelCopyBufferLayout`, the data-layout argument
  54371. * to `GPUQueue.writeTexture()`.
  54372. *
  54373. * @private
  54374. */
  54375. class GPUTexelCopyBufferLayout {
  54376. constructor() {
  54377. /**
  54378. * The byte offset within the source data where the texel data begins.
  54379. *
  54380. * @type {number}
  54381. * @default 0
  54382. */
  54383. this.offset = 0;
  54384. /**
  54385. * The stride, in bytes, between rows of texel blocks.
  54386. *
  54387. * @type {number|undefined}
  54388. */
  54389. this.bytesPerRow = undefined;
  54390. /**
  54391. * The number of texel block rows per single image of the texture.
  54392. *
  54393. * @type {number|undefined}
  54394. */
  54395. this.rowsPerImage = undefined;
  54396. }
  54397. /**
  54398. * Resets the descriptor to its default state.
  54399. */
  54400. reset() {
  54401. this.offset = 0;
  54402. this.bytesPerRow = undefined;
  54403. this.rowsPerImage = undefined;
  54404. }
  54405. }
  54406. /**
  54407. * Reusable descriptor for `GPUCopyExternalImageSourceInfo`, the source argument
  54408. * to `GPUQueue.copyExternalImageToTexture()`.
  54409. *
  54410. * @private
  54411. */
  54412. class GPUCopyExternalImageSourceInfo {
  54413. constructor() {
  54414. /**
  54415. * The image-like source.
  54416. *
  54417. * @type {?(ImageBitmap|ImageData|HTMLImageElement|HTMLVideoElement|VideoFrame|HTMLCanvasElement|OffscreenCanvas)}
  54418. * @default null
  54419. */
  54420. this.source = null;
  54421. /**
  54422. * The origin offset within the source.
  54423. *
  54424. * @type {{x: number, y: number}}
  54425. */
  54426. this.origin = { x: 0, y: 0 };
  54427. /**
  54428. * Whether the source is flipped vertically before copying.
  54429. *
  54430. * @type {boolean}
  54431. * @default false
  54432. */
  54433. this.flipY = false;
  54434. }
  54435. /**
  54436. * Resets the descriptor to its default state.
  54437. */
  54438. reset() {
  54439. this.source = null;
  54440. this.origin.x = 0;
  54441. this.origin.y = 0;
  54442. this.flipY = false;
  54443. }
  54444. }
  54445. /**
  54446. * Reusable descriptor for `GPUCopyExternalImageDestInfo`, the destination
  54447. * argument to `GPUQueue.copyExternalImageToTexture()`.
  54448. *
  54449. * @private
  54450. * @augments GPUTexelCopyTextureInfo
  54451. */
  54452. class GPUCopyExternalImageDestInfo extends GPUTexelCopyTextureInfo {
  54453. constructor() {
  54454. super();
  54455. /**
  54456. * The predefined color space the destination texture is interpreted in.
  54457. *
  54458. * @type {string}
  54459. * @default 'srgb'
  54460. */
  54461. this.colorSpace = 'srgb';
  54462. /**
  54463. * Whether the destination texture has premultiplied alpha.
  54464. *
  54465. * @type {boolean}
  54466. * @default false
  54467. */
  54468. this.premultipliedAlpha = false;
  54469. }
  54470. /**
  54471. * Resets the descriptor to its default state.
  54472. */
  54473. reset() {
  54474. super.reset();
  54475. this.colorSpace = 'srgb';
  54476. this.premultipliedAlpha = false;
  54477. }
  54478. }
  54479. /**
  54480. * Reusable descriptor for `GPUExtent3D` in its dictionary form, used by
  54481. * `GPUQueue.writeTexture()`, `GPUQueue.copyExternalImageToTexture()` and
  54482. * the various `GPUCommandEncoder` copy methods.
  54483. *
  54484. * @private
  54485. */
  54486. class GPUExtent3D {
  54487. constructor() {
  54488. /**
  54489. * The width of the extent.
  54490. *
  54491. * @type {number}
  54492. * @default 0
  54493. */
  54494. this.width = 0;
  54495. /**
  54496. * The height of the extent.
  54497. *
  54498. * @type {number}
  54499. * @default 1
  54500. */
  54501. this.height = 1;
  54502. /**
  54503. * The depth (for 3D textures) or number of array layers.
  54504. *
  54505. * @type {number}
  54506. * @default 1
  54507. */
  54508. this.depthOrArrayLayers = 1;
  54509. }
  54510. /**
  54511. * Resets the descriptor to its default state.
  54512. */
  54513. reset() {
  54514. this.width = 0;
  54515. this.height = 1;
  54516. this.depthOrArrayLayers = 1;
  54517. }
  54518. }
  54519. const _bufferDescriptor$4 = new GPUBufferDescriptor();
  54520. const _commandEncoderDescriptor$3 = new GPUCommandEncoderDescriptor();
  54521. const _samplerDescriptor = new GPUSamplerDescriptor();
  54522. const _texelCopyTextureInfo = new GPUTexelCopyTextureInfo();
  54523. const _texelCopyBufferInfo = new GPUTexelCopyBufferInfo();
  54524. const _texelCopyBufferLayout = new GPUTexelCopyBufferLayout();
  54525. const _copyExternalImageSourceInfo = new GPUCopyExternalImageSourceInfo();
  54526. const _copyExternalImageDestInfo = new GPUCopyExternalImageDestInfo();
  54527. const _textureDescriptor = new GPUTextureDescriptor();
  54528. const _extent3D$1 = new GPUExtent3D();
  54529. const _compareToWebGPU = {
  54530. [ NeverCompare ]: 'never',
  54531. [ LessCompare ]: 'less',
  54532. [ EqualCompare ]: 'equal',
  54533. [ LessEqualCompare ]: 'less-equal',
  54534. [ GreaterCompare ]: 'greater',
  54535. [ GreaterEqualCompare ]: 'greater-equal',
  54536. [ AlwaysCompare ]: 'always',
  54537. [ NotEqualCompare ]: 'not-equal'
  54538. };
  54539. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  54540. function writeTextureLayer( device, textureGPU, mipLevel, layerIndex, mipmap, bytesPerImage, bytesPerRow, rowsPerImage, textureWidth, textureHeight ) {
  54541. _texelCopyTextureInfo.texture = textureGPU;
  54542. _texelCopyTextureInfo.mipLevel = mipLevel;
  54543. _texelCopyTextureInfo.origin.z = layerIndex;
  54544. _texelCopyBufferLayout.offset = layerIndex * bytesPerImage;
  54545. _texelCopyBufferLayout.bytesPerRow = bytesPerRow;
  54546. _texelCopyBufferLayout.rowsPerImage = rowsPerImage;
  54547. _extent3D$1.width = textureWidth;
  54548. _extent3D$1.height = textureHeight;
  54549. device.queue.writeTexture(
  54550. _texelCopyTextureInfo,
  54551. mipmap.data,
  54552. _texelCopyBufferLayout,
  54553. _extent3D$1
  54554. );
  54555. _texelCopyTextureInfo.reset();
  54556. _texelCopyBufferLayout.reset();
  54557. _extent3D$1.reset();
  54558. }
  54559. /**
  54560. * A WebGPU backend utility module for managing textures.
  54561. *
  54562. * @private
  54563. */
  54564. class WebGPUTextureUtils {
  54565. /**
  54566. * Constructs a new utility object.
  54567. *
  54568. * @param {WebGPUBackend} backend - The WebGPU backend.
  54569. */
  54570. constructor( backend ) {
  54571. /**
  54572. * A reference to the WebGPU backend.
  54573. *
  54574. * @type {WebGPUBackend}
  54575. */
  54576. this.backend = backend;
  54577. /**
  54578. * A reference to the pass utils.
  54579. *
  54580. * @type {?WebGPUTexturePassUtils}
  54581. * @default null
  54582. */
  54583. this._passUtils = null;
  54584. /**
  54585. * A dictionary for managing default textures. The key
  54586. * is the texture format, the value the texture object.
  54587. *
  54588. * @type {Object<string,Texture>}
  54589. */
  54590. this.defaultTexture = {};
  54591. /**
  54592. * A dictionary for managing default cube textures. The key
  54593. * is the texture format, the value the texture object.
  54594. *
  54595. * @type {Object<string,CubeTexture>}
  54596. */
  54597. this.defaultCubeTexture = {};
  54598. /**
  54599. * A default video frame.
  54600. *
  54601. * @type {?VideoFrame}
  54602. * @default null
  54603. */
  54604. this.defaultVideoFrame = null;
  54605. /**
  54606. * A cache of shared texture samplers.
  54607. *
  54608. * @type {Map<string, Object>}
  54609. */
  54610. this._samplerCache = new Map();
  54611. }
  54612. /**
  54613. * Creates a GPU sampler for the given texture.
  54614. *
  54615. * @param {Sampler} binding - The sampler binding to update.
  54616. * @return {string} The current sampler key.
  54617. */
  54618. updateSampler( binding ) {
  54619. const backend = this.backend;
  54620. const texture = binding.texture;
  54621. const textureNode = binding.textureNode;
  54622. const samplerKey = texture.minFilter + '-' + texture.magFilter + '-' +
  54623. texture.wrapS + '-' + texture.wrapT + '-' + ( texture.wrapR || '0' ) + '-' +
  54624. texture.anisotropy + '-' + ( texture.isDepthTexture === true ? 1 : 0 ) + '-' +
  54625. ( texture.compareFunction !== null && textureNode.compareNode !== null ? texture.compareFunction : 0 );
  54626. let samplerData = this._samplerCache.get( samplerKey );
  54627. if ( samplerData === undefined ) {
  54628. _samplerDescriptor.addressModeU = this._convertAddressMode( texture.wrapS );
  54629. _samplerDescriptor.addressModeV = this._convertAddressMode( texture.wrapT );
  54630. _samplerDescriptor.addressModeW = this._convertAddressMode( texture.wrapR );
  54631. _samplerDescriptor.magFilter = this._convertFilterMode( texture.magFilter );
  54632. _samplerDescriptor.minFilter = this._convertFilterMode( texture.minFilter );
  54633. _samplerDescriptor.mipmapFilter = this._convertMipmapFilterMode( texture.minFilter );
  54634. // Depth textures without compare function must use non-filtering (nearest) sampling
  54635. if ( texture.isDepthTexture && ( texture.compareFunction === null || textureNode.compareNode === null ) ) {
  54636. _samplerDescriptor.magFilter = GPUFilterMode.Nearest;
  54637. _samplerDescriptor.minFilter = GPUFilterMode.Nearest;
  54638. _samplerDescriptor.mipmapFilter = GPUFilterMode.Nearest;
  54639. }
  54640. // anisotropy can only be used when all filter modes are set to linear.
  54641. if ( _samplerDescriptor.magFilter === GPUFilterMode.Linear && _samplerDescriptor.minFilter === GPUFilterMode.Linear && _samplerDescriptor.mipmapFilter === GPUFilterMode.Linear ) {
  54642. _samplerDescriptor.maxAnisotropy = texture.anisotropy;
  54643. }
  54644. if ( texture.isDepthTexture && texture.compareFunction !== null && textureNode.compareNode !== null && backend.hasCompatibility( Compatibility.TEXTURE_COMPARE ) ) {
  54645. _samplerDescriptor.compare = _compareToWebGPU[ texture.compareFunction ];
  54646. }
  54647. const sampler = backend.device.createSampler( _samplerDescriptor );
  54648. _samplerDescriptor.reset();
  54649. samplerData = { sampler, usedTimes: 0 };
  54650. this._samplerCache.set( samplerKey, samplerData );
  54651. }
  54652. const bindingData = backend.get( binding );
  54653. if ( bindingData.sampler !== samplerData.sampler ) {
  54654. // release the previous sampler (if any) so it can be deleted when unused
  54655. this._releaseSampler( bindingData );
  54656. // update to new sampler data
  54657. bindingData.samplerKey = samplerKey;
  54658. bindingData.sampler = samplerData.sampler;
  54659. samplerData.usedTimes ++;
  54660. }
  54661. return samplerKey;
  54662. }
  54663. /**
  54664. * Frees the GPU sampler referenced by the given sampler binding.
  54665. *
  54666. * @param {Sampler} binding - The sampler binding to free.
  54667. */
  54668. destroySampler( binding ) {
  54669. this._releaseSampler( this.backend.get( binding ) );
  54670. }
  54671. /**
  54672. * Releases the pooled sampler referenced by the given binding data and
  54673. * removes it from the cache when no binding references it anymore.
  54674. *
  54675. * @private
  54676. * @param {Object} bindingData - The binding data holding the sampler reference.
  54677. */
  54678. _releaseSampler( bindingData ) {
  54679. if ( bindingData.sampler !== undefined ) {
  54680. const samplerData = this._samplerCache.get( bindingData.samplerKey );
  54681. samplerData.usedTimes --;
  54682. if ( samplerData.usedTimes === 0 ) {
  54683. this._samplerCache.delete( bindingData.samplerKey );
  54684. }
  54685. bindingData.sampler = undefined;
  54686. bindingData.samplerKey = undefined;
  54687. }
  54688. }
  54689. /**
  54690. * Creates a default texture for the given texture that can be used
  54691. * as a placeholder until the actual texture is ready for usage.
  54692. *
  54693. * @param {Texture} texture - The texture to create a default texture for.
  54694. */
  54695. createDefaultTexture( texture ) {
  54696. let textureGPU;
  54697. const format = getFormat( texture, this.backend.device );
  54698. if ( texture.isCubeTexture ) {
  54699. textureGPU = this._getDefaultCubeTextureGPU( format );
  54700. } else {
  54701. textureGPU = this._getDefaultTextureGPU( format );
  54702. }
  54703. this.backend.get( texture ).texture = textureGPU;
  54704. }
  54705. /**
  54706. * Defines a texture on the GPU for the given texture object.
  54707. *
  54708. * @param {Texture} texture - The texture.
  54709. * @param {Object} [options={}] - Optional configuration parameter.
  54710. */
  54711. createTexture( texture, options = {} ) {
  54712. const backend = this.backend;
  54713. const textureData = backend.get( texture );
  54714. if ( textureData.initialized ) {
  54715. // Skip creation for external XR textures - they are already set up
  54716. if ( textureData.externalTexture === true ) {
  54717. return;
  54718. }
  54719. throw new Error( 'THREE.WebGPUTextureUtils: Texture already initialized.' );
  54720. }
  54721. if ( texture.isExternalTexture ) {
  54722. textureData.texture = texture.sourceTexture;
  54723. textureData.initialized = true;
  54724. return;
  54725. }
  54726. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  54727. if ( options.levels === undefined ) options.levels = 1;
  54728. if ( options.depth === undefined ) options.depth = 1;
  54729. const { width, height, depth, levels } = options;
  54730. if ( texture.isFramebufferTexture ) {
  54731. if ( options.renderTarget ) {
  54732. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  54733. } else {
  54734. options.format = this.backend.utils.getPreferredCanvasFormat();
  54735. }
  54736. }
  54737. const dimension = this._getDimension( texture );
  54738. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  54739. textureData.format = format;
  54740. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  54741. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  54742. if ( texture.isStorageTexture === true ) {
  54743. usage |= GPUTextureUsage.STORAGE_BINDING;
  54744. }
  54745. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true && format !== GPUTextureFormat.RGB9E5UFloat ) {
  54746. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  54747. }
  54748. const renderTarget = texture.renderTarget;
  54749. // when the multisampled data are discarded, try to use a transient attachment if possible
  54750. if ( texture.isDepthTexture === true && primarySamples > 1 && GPUTextureUsage.TRANSIENT_ATTACHMENT !== undefined ) {
  54751. if ( renderTarget?.storeMultisampledDepthBuffer === false && ( renderTarget.stencilBuffer === false || renderTarget.storeMultisampledStencilBuffer === false ) ) {
  54752. usage = GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TRANSIENT_ATTACHMENT;
  54753. }
  54754. }
  54755. const textureDescriptorGPU = new GPUTextureDescriptor();
  54756. textureDescriptorGPU.label = texture.name;
  54757. textureDescriptorGPU.size.width = width;
  54758. textureDescriptorGPU.size.height = height;
  54759. textureDescriptorGPU.size.depthOrArrayLayers = depth;
  54760. textureDescriptorGPU.mipLevelCount = levels;
  54761. textureDescriptorGPU.sampleCount = primarySamples;
  54762. textureDescriptorGPU.dimension = dimension;
  54763. textureDescriptorGPU.format = format;
  54764. textureDescriptorGPU.usage = usage;
  54765. // texture creation
  54766. if ( format === undefined ) {
  54767. warn( 'WebGPURenderer: Texture format not supported.' );
  54768. this.createDefaultTexture( texture );
  54769. return;
  54770. }
  54771. if ( texture.isCubeTexture ) {
  54772. textureDescriptorGPU.textureBindingViewDimension = GPUTextureViewDimension.Cube;
  54773. }
  54774. try {
  54775. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  54776. } catch ( e ) {
  54777. warn( 'WebGPURenderer: Failed to create texture with descriptor:', textureDescriptorGPU );
  54778. this.createDefaultTexture( texture );
  54779. return;
  54780. }
  54781. if ( isMSAA ) {
  54782. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  54783. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  54784. msaaTextureDescriptorGPU.sampleCount = samples;
  54785. msaaTextureDescriptorGPU.mipLevelCount = 1; // See https://www.w3.org/TR/webgpu/#texture-creation
  54786. // when the multisampled data are discarded, try to use a transient attachment if possible
  54787. if ( renderTarget?.storeMultisampledColorBuffer === false && GPUTextureUsage.TRANSIENT_ATTACHMENT !== undefined ) {
  54788. msaaTextureDescriptorGPU.usage = GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TRANSIENT_ATTACHMENT;
  54789. }
  54790. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  54791. }
  54792. textureData.initialized = true;
  54793. textureData.textureDescriptorGPU = textureDescriptorGPU;
  54794. }
  54795. /**
  54796. * Destroys the GPU data for the given texture object.
  54797. *
  54798. * @param {Texture} texture - The texture.
  54799. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  54800. */
  54801. destroyTexture( texture, isDefaultTexture = false ) {
  54802. const backend = this.backend;
  54803. const textureData = backend.get( texture );
  54804. if ( textureData.texture !== undefined && isDefaultTexture === false && texture.isExternalTexture !== true ) textureData.texture.destroy();
  54805. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  54806. backend.delete( texture );
  54807. }
  54808. /**
  54809. * Generates mipmaps for the given texture.
  54810. *
  54811. * @param {Texture} texture - The texture.
  54812. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  54813. */
  54814. generateMipmaps( texture, encoder = null ) {
  54815. const textureData = this.backend.get( texture );
  54816. this._generateMipmaps( textureData.texture, encoder );
  54817. }
  54818. /**
  54819. * Returns the color buffer representing the color
  54820. * attachment of the default framebuffer.
  54821. *
  54822. * @return {GPUTexture} The color buffer.
  54823. */
  54824. getColorBuffer() {
  54825. const backend = this.backend;
  54826. const canvasTarget = backend.renderer.getCanvasTarget();
  54827. const { width, height } = backend.getDrawingBufferSize();
  54828. const samples = backend.renderer.currentSamples;
  54829. const colorTexture = canvasTarget.colorTexture;
  54830. const colorTextureData = backend.get( colorTexture );
  54831. if ( colorTexture.width === width && colorTexture.height === height && colorTexture.samples === samples ) {
  54832. return colorTextureData.texture;
  54833. }
  54834. // recreate
  54835. let colorBuffer = colorTextureData.texture;
  54836. if ( colorBuffer ) colorBuffer.destroy();
  54837. _textureDescriptor.label = 'colorBuffer';
  54838. _textureDescriptor.size.width = width;
  54839. _textureDescriptor.size.height = height;
  54840. _textureDescriptor.sampleCount = backend.utils.getSampleCount( backend.renderer.currentSamples );
  54841. _textureDescriptor.format = backend.utils.getPreferredCanvasFormat();
  54842. _textureDescriptor.usage = GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC;
  54843. colorBuffer = backend.device.createTexture( _textureDescriptor );
  54844. _textureDescriptor.reset();
  54845. //
  54846. colorTexture.source.width = width;
  54847. colorTexture.source.height = height;
  54848. colorTexture.samples = samples;
  54849. colorTextureData.texture = colorBuffer;
  54850. return colorBuffer;
  54851. }
  54852. /**
  54853. * Returns the depth buffer representing the depth
  54854. * attachment of the default framebuffer.
  54855. *
  54856. * @param {boolean} [depth=true] - Whether depth is enabled or not.
  54857. * @param {boolean} [stencil=false] - Whether stencil is enabled or not.
  54858. * @return {GPUTexture} The depth buffer.
  54859. */
  54860. getDepthBuffer( depth = true, stencil = false ) {
  54861. const backend = this.backend;
  54862. const canvasTarget = backend.renderer.getCanvasTarget();
  54863. const { width, height } = backend.getDrawingBufferSize();
  54864. const samples = backend.renderer.currentSamples;
  54865. const depthTexture = canvasTarget.depthTexture;
  54866. if ( depthTexture.width === width &&
  54867. depthTexture.height === height &&
  54868. depthTexture.samples === samples &&
  54869. depthTexture.depth === depth &&
  54870. depthTexture.stencil === stencil ) {
  54871. return backend.get( depthTexture ).texture;
  54872. }
  54873. //
  54874. const depthTextureGPU = backend.get( depthTexture ).texture;
  54875. let format, type;
  54876. if ( stencil ) {
  54877. format = DepthStencilFormat;
  54878. type = backend.renderer.reversedDepthBuffer === true ? FloatType : UnsignedInt248Type;
  54879. } else if ( depth ) {
  54880. format = DepthFormat;
  54881. type = backend.renderer.reversedDepthBuffer === true ? FloatType : UnsignedIntType;
  54882. }
  54883. if ( depthTextureGPU !== undefined ) {
  54884. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type && depthTexture.samples === samples ) {
  54885. return depthTextureGPU;
  54886. }
  54887. this.destroyTexture( depthTexture );
  54888. }
  54889. // recreate
  54890. depthTexture.name = 'depthBuffer';
  54891. depthTexture.format = format;
  54892. depthTexture.type = type;
  54893. depthTexture.image.width = width;
  54894. depthTexture.image.height = height;
  54895. depthTexture.samples = samples;
  54896. this.createTexture( depthTexture, { width, height } );
  54897. return backend.get( depthTexture ).texture;
  54898. }
  54899. /**
  54900. * Uploads the updated texture data to the GPU.
  54901. *
  54902. * @param {Texture} texture - The texture.
  54903. * @param {Object} [options={}] - Optional configuration parameter.
  54904. */
  54905. updateTexture( texture, options ) {
  54906. const textureData = this.backend.get( texture );
  54907. const mipmaps = texture.mipmaps;
  54908. const { textureDescriptorGPU } = textureData;
  54909. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  54910. return;
  54911. // transfer texture data
  54912. if ( texture.isDataTexture ) {
  54913. if ( mipmaps.length > 0 ) {
  54914. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  54915. const mipmap = mipmaps[ i ];
  54916. this._copyBufferToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, 0, i );
  54917. }
  54918. } else {
  54919. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  54920. }
  54921. } else if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  54922. if ( texture.layerUpdates && texture.layerUpdates.size > 0 ) {
  54923. for ( const layerIndex of texture.layerUpdates ) {
  54924. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, layerIndex, texture.flipY, layerIndex );
  54925. }
  54926. texture.clearLayerUpdates();
  54927. } else {
  54928. for ( let i = 0; i < options.image.depth; i ++ ) {
  54929. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  54930. }
  54931. }
  54932. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  54933. if ( texture.isCompressedArrayTexture && texture.layerUpdates.size > 0 ) {
  54934. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU, texture.layerUpdates );
  54935. texture.clearLayerUpdates();
  54936. } else {
  54937. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  54938. }
  54939. } else if ( texture.isCubeTexture ) {
  54940. this._copyCubeMapToTexture( texture, textureData.texture, textureDescriptorGPU );
  54941. } else if ( texture.isHTMLTexture ) {
  54942. const device = this.backend.device;
  54943. const canvas = this.backend.renderer.domElement;
  54944. const image = texture.image;
  54945. if ( typeof device.queue.copyElementImageToTexture !== 'function' ) return;
  54946. // Skip the first frame — the element needs a paint record first.
  54947. if ( ! textureData.hasPaintCallback ) {
  54948. textureData.hasPaintCallback = true;
  54949. canvas.requestPaint();
  54950. return;
  54951. }
  54952. const width = textureDescriptorGPU.size.width;
  54953. const height = textureDescriptorGPU.size.height;
  54954. if ( device.queue.copyElementImageToTexture.length === 2 ) {
  54955. // Chrome 150+
  54956. device.queue.copyElementImageToTexture(
  54957. { source: image },
  54958. {
  54959. destination: { texture: textureData.texture },
  54960. width: width,
  54961. height: height
  54962. }
  54963. );
  54964. } else {
  54965. // Chrome 138 - 149
  54966. device.queue.copyElementImageToTexture(
  54967. image, width, height,
  54968. { texture: textureData.texture }
  54969. );
  54970. }
  54971. if ( texture.flipY ) {
  54972. this._flipY( textureData.texture, textureDescriptorGPU );
  54973. }
  54974. } else {
  54975. if ( mipmaps.length > 0 ) {
  54976. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  54977. const mipmap = mipmaps[ i ];
  54978. this._copyImageToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha, i );
  54979. }
  54980. } else {
  54981. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha );
  54982. }
  54983. }
  54984. //
  54985. textureData.version = texture.version;
  54986. }
  54987. /**
  54988. * Returns texture data as a typed array.
  54989. *
  54990. * @async
  54991. * @param {Texture} texture - The texture to copy.
  54992. * @param {number} x - The x coordinate of the copy origin.
  54993. * @param {number} y - The y coordinate of the copy origin.
  54994. * @param {number} width - The width of the copy.
  54995. * @param {number} height - The height of the copy.
  54996. * @param {number} faceIndex - The face index.
  54997. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  54998. */
  54999. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  55000. const device = this.backend.device;
  55001. const textureData = this.backend.get( texture );
  55002. const textureGPU = textureData.texture;
  55003. const format = textureData.textureDescriptorGPU.format;
  55004. const bytesPerTexel = this._getBytesPerTexel( format );
  55005. let bytesPerRow = width * bytesPerTexel;
  55006. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  55007. _bufferDescriptor$4.size = ( ( height - 1 ) * bytesPerRow ) + ( width * bytesPerTexel ); // see https://github.com/mrdoob/three.js/issues/31658#issuecomment-3229442010
  55008. _bufferDescriptor$4.usage = GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ;
  55009. const readBuffer = device.createBuffer( _bufferDescriptor$4 );
  55010. _bufferDescriptor$4.reset();
  55011. const encoder = device.createCommandEncoder( _commandEncoderDescriptor$3 );
  55012. _texelCopyTextureInfo.texture = textureGPU;
  55013. _texelCopyTextureInfo.origin.x = x;
  55014. _texelCopyTextureInfo.origin.y = y;
  55015. _texelCopyTextureInfo.origin.z = faceIndex;
  55016. _texelCopyBufferInfo.buffer = readBuffer;
  55017. _texelCopyBufferInfo.bytesPerRow = bytesPerRow;
  55018. _extent3D$1.width = width;
  55019. _extent3D$1.height = height;
  55020. encoder.copyTextureToBuffer(
  55021. _texelCopyTextureInfo,
  55022. _texelCopyBufferInfo,
  55023. _extent3D$1
  55024. );
  55025. _texelCopyTextureInfo.reset();
  55026. _texelCopyBufferInfo.reset();
  55027. _extent3D$1.reset();
  55028. const typedArrayType = this._getTypedArrayType( format );
  55029. submit( device, encoder.finish() );
  55030. await readBuffer.mapAsync( GPUMapMode.READ );
  55031. const buffer = readBuffer.getMappedRange().slice();
  55032. readBuffer.destroy();
  55033. return new typedArrayType( buffer );
  55034. }
  55035. /**
  55036. * Frees all internal resources.
  55037. */
  55038. dispose() {
  55039. this._samplerCache.clear();
  55040. }
  55041. /**
  55042. * Returns the default GPU texture for the given format.
  55043. *
  55044. * @private
  55045. * @param {string} format - The GPU format.
  55046. * @return {GPUTexture} The GPU texture.
  55047. */
  55048. _getDefaultTextureGPU( format ) {
  55049. let defaultTexture = this.defaultTexture[ format ];
  55050. if ( defaultTexture === undefined ) {
  55051. const texture = new Texture();
  55052. texture.minFilter = NearestFilter;
  55053. texture.magFilter = NearestFilter;
  55054. this.createTexture( texture, { width: 1, height: 1, format } );
  55055. this.defaultTexture[ format ] = defaultTexture = texture;
  55056. }
  55057. return this.backend.get( defaultTexture ).texture;
  55058. }
  55059. /**
  55060. * Returns the default GPU cube texture for the given format.
  55061. *
  55062. * @private
  55063. * @param {string} format - The GPU format.
  55064. * @return {GPUTexture} The GPU texture.
  55065. */
  55066. _getDefaultCubeTextureGPU( format ) {
  55067. let defaultCubeTexture = this.defaultCubeTexture[ format ];
  55068. if ( defaultCubeTexture === undefined ) {
  55069. const texture = new CubeTexture();
  55070. texture.minFilter = NearestFilter;
  55071. texture.magFilter = NearestFilter;
  55072. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  55073. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  55074. }
  55075. return this.backend.get( defaultCubeTexture ).texture;
  55076. }
  55077. /**
  55078. * Uploads cube texture image data to the GPU memory.
  55079. *
  55080. * @private
  55081. * @param {CubeTexture} texture - The cube texture.
  55082. * @param {GPUTexture} textureGPU - The GPU texture.
  55083. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  55084. */
  55085. _copyCubeMapToTexture( texture, textureGPU, textureDescriptorGPU ) {
  55086. const images = texture.images;
  55087. const mipmaps = texture.mipmaps;
  55088. for ( let i = 0; i < 6; i ++ ) {
  55089. const image = images[ i ];
  55090. const flipIndex = texture.flipY === true ? _flipMap[ i ] : i;
  55091. if ( image.isDataTexture ) {
  55092. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY );
  55093. } else {
  55094. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha );
  55095. }
  55096. for ( let j = 0; j < mipmaps.length; j ++ ) {
  55097. const mipmap = mipmaps[ j ];
  55098. const image = mipmap.images[ i ];
  55099. if ( image.isDataTexture ) {
  55100. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, 0, j + 1 );
  55101. } else {
  55102. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha, j + 1 );
  55103. }
  55104. }
  55105. }
  55106. }
  55107. /**
  55108. * Uploads texture image data to the GPU memory.
  55109. *
  55110. * @private
  55111. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  55112. * @param {GPUTexture} textureGPU - The GPU texture.
  55113. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  55114. * @param {number} originDepth - The origin depth.
  55115. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  55116. * @param {boolean} premultiplyAlpha - Whether the texture should have its RGB channels premultiplied by the alpha channel or not.
  55117. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  55118. */
  55119. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, premultiplyAlpha, mipLevel = 0 ) {
  55120. const device = this.backend.device;
  55121. const width = ( mipLevel > 0 ) ? image.width : textureDescriptorGPU.size.width;
  55122. const height = ( mipLevel > 0 ) ? image.height : textureDescriptorGPU.size.height;
  55123. _copyExternalImageSourceInfo.source = image;
  55124. _copyExternalImageSourceInfo.flipY = flipY;
  55125. _copyExternalImageDestInfo.texture = textureGPU;
  55126. _copyExternalImageDestInfo.mipLevel = mipLevel;
  55127. _copyExternalImageDestInfo.origin.z = originDepth;
  55128. _copyExternalImageDestInfo.premultipliedAlpha = premultiplyAlpha;
  55129. _extent3D$1.width = width;
  55130. _extent3D$1.height = height;
  55131. try {
  55132. device.queue.copyExternalImageToTexture(
  55133. _copyExternalImageSourceInfo,
  55134. _copyExternalImageDestInfo,
  55135. _extent3D$1
  55136. );
  55137. // try/catch has been added to fix bad video frame data on certain devices, see #32391
  55138. } catch ( _ ) {
  55139. } finally {
  55140. _copyExternalImageSourceInfo.reset();
  55141. _copyExternalImageDestInfo.reset();
  55142. _extent3D$1.reset();
  55143. }
  55144. }
  55145. /**
  55146. * Returns the pass utils singleton.
  55147. *
  55148. * @private
  55149. * @return {WebGPUTexturePassUtils} The utils instance.
  55150. */
  55151. _getPassUtils() {
  55152. let passUtils = this._passUtils;
  55153. if ( passUtils === null ) {
  55154. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  55155. }
  55156. return passUtils;
  55157. }
  55158. /**
  55159. * Generates mipmaps for the given GPU texture.
  55160. *
  55161. * @private
  55162. * @param {GPUTexture} textureGPU - The GPU texture object.
  55163. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  55164. */
  55165. _generateMipmaps( textureGPU, encoder = null ) {
  55166. this._getPassUtils().generateMipmaps( textureGPU, encoder );
  55167. }
  55168. /**
  55169. * Flip the contents of the given GPU texture along its vertical axis.
  55170. *
  55171. * @private
  55172. * @param {GPUTexture} textureGPU - The GPU texture object.
  55173. * @param {Object} textureDescriptorGPU - The texture descriptor.
  55174. * @param {number} [originDepth=0] - The origin depth.
  55175. */
  55176. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  55177. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  55178. }
  55179. /**
  55180. * Uploads texture buffer data to the GPU memory.
  55181. *
  55182. * @private
  55183. * @param {Object} image - An object defining the image buffer data.
  55184. * @param {GPUTexture} textureGPU - The GPU texture.
  55185. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  55186. * @param {number} originDepth - The origin depth.
  55187. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  55188. * @param {number} [depth=0] - The depth offset when copying array or 3D texture data.
  55189. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  55190. */
  55191. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0, mipLevel = 0 ) {
  55192. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  55193. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  55194. const device = this.backend.device;
  55195. const data = image.data;
  55196. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  55197. const bytesPerRow = image.width * bytesPerTexel;
  55198. _texelCopyTextureInfo.texture = textureGPU;
  55199. _texelCopyTextureInfo.mipLevel = mipLevel;
  55200. _texelCopyTextureInfo.origin.z = originDepth;
  55201. _texelCopyBufferLayout.offset = image.width * image.height * bytesPerTexel * depth;
  55202. _texelCopyBufferLayout.bytesPerRow = bytesPerRow;
  55203. _extent3D$1.width = image.width;
  55204. _extent3D$1.height = image.height;
  55205. device.queue.writeTexture(
  55206. _texelCopyTextureInfo,
  55207. data,
  55208. _texelCopyBufferLayout,
  55209. _extent3D$1
  55210. );
  55211. _texelCopyTextureInfo.reset();
  55212. _texelCopyBufferLayout.reset();
  55213. _extent3D$1.reset();
  55214. if ( flipY === true ) {
  55215. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  55216. }
  55217. }
  55218. /**
  55219. * Uploads compressed texture data to the GPU memory.
  55220. *
  55221. * @private
  55222. * @param {Array<Object>} mipmaps - An array with mipmap data.
  55223. * @param {GPUTexture} textureGPU - The GPU texture.
  55224. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  55225. * @param {?Set<number>} [layerUpdates=null] - The layer indices to update.
  55226. */
  55227. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU, layerUpdates = null ) {
  55228. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  55229. const device = this.backend.device;
  55230. const blockData = this._getBlockData( textureDescriptorGPU.format );
  55231. const isArrayTexture = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  55232. const activeLayerUpdates = layerUpdates && layerUpdates.size > 0 ? layerUpdates : null;
  55233. for ( let i = 0; i < mipmaps.length; i ++ ) {
  55234. const mipmap = mipmaps[ i ];
  55235. const width = mipmap.width;
  55236. const height = mipmap.height;
  55237. const depth = isArrayTexture ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  55238. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  55239. const rowsPerImage = Math.ceil( height / blockData.height );
  55240. const bytesPerImage = bytesPerRow * rowsPerImage;
  55241. const textureWidth = Math.ceil( width / blockData.width ) * blockData.width;
  55242. const textureHeight = rowsPerImage * blockData.height;
  55243. if ( activeLayerUpdates !== null ) {
  55244. for ( const layerIndex of activeLayerUpdates ) {
  55245. writeTextureLayer( device, textureGPU, i, layerIndex, mipmap, bytesPerImage, bytesPerRow, rowsPerImage, textureWidth, textureHeight );
  55246. }
  55247. } else {
  55248. for ( let layerIndex = 0; layerIndex < depth; layerIndex ++ ) {
  55249. writeTextureLayer( device, textureGPU, i, layerIndex, mipmap, bytesPerImage, bytesPerRow, rowsPerImage, textureWidth, textureHeight );
  55250. }
  55251. }
  55252. }
  55253. }
  55254. /**
  55255. * This method is only relevant for compressed texture formats. It returns a block
  55256. * data descriptor for the given GPU compressed texture format.
  55257. *
  55258. * @private
  55259. * @param {string} format - The GPU compressed texture format.
  55260. * @return {Object} The block data descriptor.
  55261. */
  55262. _getBlockData( format ) {
  55263. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  55264. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  55265. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  55266. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSnorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  55267. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  55268. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  55269. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  55270. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  55271. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  55272. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  55273. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  55274. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  55275. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  55276. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  55277. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  55278. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  55279. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  55280. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  55281. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  55282. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  55283. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  55284. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  55285. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  55286. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  55287. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  55288. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  55289. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  55290. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  55291. }
  55292. /**
  55293. * Converts the three.js uv wrapping constants to GPU address mode constants.
  55294. *
  55295. * @private
  55296. * @param {number} value - The three.js constant defining a uv wrapping mode.
  55297. * @return {string} The GPU address mode.
  55298. */
  55299. _convertAddressMode( value ) {
  55300. let addressMode = GPUAddressMode.ClampToEdge;
  55301. if ( value === RepeatWrapping ) {
  55302. addressMode = GPUAddressMode.Repeat;
  55303. } else if ( value === MirroredRepeatWrapping ) {
  55304. addressMode = GPUAddressMode.MirrorRepeat;
  55305. }
  55306. return addressMode;
  55307. }
  55308. /**
  55309. * Converts the three.js filter constants to GPU filter constants.
  55310. *
  55311. * @private
  55312. * @param {number} value - The three.js constant defining a filter mode.
  55313. * @return {string} The GPU filter mode.
  55314. */
  55315. _convertFilterMode( value ) {
  55316. let filterMode = GPUFilterMode.Linear;
  55317. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  55318. filterMode = GPUFilterMode.Nearest;
  55319. }
  55320. return filterMode;
  55321. }
  55322. /**
  55323. * Converts the three.js filter constants to a GPU mipmap filter constant.
  55324. * Unlike `_convertFilterMode`, this extracts the between-mip-level filtering
  55325. * axis from the combined three.js constant rather than the within-level axis.
  55326. *
  55327. * @private
  55328. * @param {number} value - The three.js constant defining a filter mode.
  55329. * @return {string} The GPU mipmap filter mode.
  55330. */
  55331. _convertMipmapFilterMode( value ) {
  55332. if ( value === NearestMipmapLinearFilter || value === LinearMipmapLinearFilter ) {
  55333. return GPUFilterMode.Linear;
  55334. }
  55335. return GPUFilterMode.Nearest;
  55336. }
  55337. /**
  55338. * Returns the bytes-per-texel value for the given GPU texture format.
  55339. *
  55340. * @private
  55341. * @param {string} format - The GPU texture format.
  55342. * @return {number} The bytes-per-texel.
  55343. */
  55344. _getBytesPerTexel( format ) {
  55345. // 8-bit formats
  55346. if ( format === GPUTextureFormat.R8Unorm ||
  55347. format === GPUTextureFormat.R8Snorm ||
  55348. format === GPUTextureFormat.R8Uint ||
  55349. format === GPUTextureFormat.R8Sint ) return 1;
  55350. // 16-bit formats
  55351. if ( format === GPUTextureFormat.R16Uint ||
  55352. format === GPUTextureFormat.R16Sint ||
  55353. format === GPUTextureFormat.R16Float ||
  55354. format === GPUTextureFormat.RG8Unorm ||
  55355. format === GPUTextureFormat.RG8Snorm ||
  55356. format === GPUTextureFormat.RG8Uint ||
  55357. format === GPUTextureFormat.RG8Sint ||
  55358. format === GPUTextureFormat.R16Unorm ||
  55359. format === GPUTextureFormat.R16Snorm ) return 2;
  55360. // 32-bit formats
  55361. if ( format === GPUTextureFormat.R32Uint ||
  55362. format === GPUTextureFormat.R32Sint ||
  55363. format === GPUTextureFormat.R32Float ||
  55364. format === GPUTextureFormat.RG16Uint ||
  55365. format === GPUTextureFormat.RG16Sint ||
  55366. format === GPUTextureFormat.RG16Float ||
  55367. format === GPUTextureFormat.RGBA8Unorm ||
  55368. format === GPUTextureFormat.RGBA8UnormSRGB ||
  55369. format === GPUTextureFormat.RGBA8Snorm ||
  55370. format === GPUTextureFormat.RGBA8Uint ||
  55371. format === GPUTextureFormat.RGBA8Sint ||
  55372. format === GPUTextureFormat.BGRA8Unorm ||
  55373. format === GPUTextureFormat.BGRA8UnormSRGB ||
  55374. format === GPUTextureFormat.RG16Unorm ||
  55375. format === GPUTextureFormat.RG16Snorm ||
  55376. // Packed 32-bit formats
  55377. format === GPUTextureFormat.RGB9E5UFloat ||
  55378. format === GPUTextureFormat.RGB10A2Unorm ||
  55379. format === GPUTextureFormat.RG11B10UFloat ||
  55380. format === GPUTextureFormat.Depth32Float ||
  55381. format === GPUTextureFormat.Depth24Plus ||
  55382. format === GPUTextureFormat.Depth24PlusStencil8 ||
  55383. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  55384. // 64-bit formats
  55385. if ( format === GPUTextureFormat.RG32Uint ||
  55386. format === GPUTextureFormat.RG32Sint ||
  55387. format === GPUTextureFormat.RG32Float ||
  55388. format === GPUTextureFormat.RGBA16Uint ||
  55389. format === GPUTextureFormat.RGBA16Sint ||
  55390. format === GPUTextureFormat.RGBA16Float ||
  55391. format === GPUTextureFormat.RGBA16Unorm ||
  55392. format === GPUTextureFormat.RGBA16Snorm ) return 8;
  55393. // 128-bit formats
  55394. if ( format === GPUTextureFormat.RGBA32Uint ||
  55395. format === GPUTextureFormat.RGBA32Sint ||
  55396. format === GPUTextureFormat.RGBA32Float ) return 16;
  55397. }
  55398. /**
  55399. * Returns the corresponding typed array type for the given GPU texture format.
  55400. *
  55401. * @private
  55402. * @param {string} format - The GPU texture format.
  55403. * @return {TypedArray.constructor} The typed array type.
  55404. */
  55405. _getTypedArrayType( format ) {
  55406. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  55407. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  55408. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  55409. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  55410. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  55411. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  55412. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  55413. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  55414. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  55415. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  55416. if ( format === GPUTextureFormat.RGBA8Unorm || format === GPUTextureFormat.RGBA8UnormSRGB ) return Uint8Array;
  55417. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  55418. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  55419. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  55420. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  55421. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  55422. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  55423. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  55424. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  55425. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  55426. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  55427. if ( format === GPUTextureFormat.R16Unorm ) return Uint16Array;
  55428. if ( format === GPUTextureFormat.R16Snorm ) return Int16Array;
  55429. if ( format === GPUTextureFormat.RG16Unorm ) return Uint16Array;
  55430. if ( format === GPUTextureFormat.RG16Snorm ) return Int16Array;
  55431. if ( format === GPUTextureFormat.RGBA16Unorm ) return Uint16Array;
  55432. if ( format === GPUTextureFormat.RGBA16Snorm ) return Int16Array;
  55433. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  55434. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  55435. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  55436. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  55437. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  55438. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  55439. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  55440. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  55441. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  55442. if ( format === GPUTextureFormat.BGRA8Unorm || format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  55443. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  55444. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  55445. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  55446. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  55447. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  55448. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  55449. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  55450. }
  55451. /**
  55452. * Returns the GPU dimensions for the given texture.
  55453. *
  55454. * @private
  55455. * @param {Texture} texture - The texture.
  55456. * @return {string} The GPU dimension.
  55457. */
  55458. _getDimension( texture ) {
  55459. let dimension;
  55460. if ( texture.is3DTexture || texture.isData3DTexture ) {
  55461. dimension = GPUTextureDimension.ThreeD;
  55462. } else {
  55463. dimension = GPUTextureDimension.TwoD;
  55464. }
  55465. return dimension;
  55466. }
  55467. }
  55468. /**
  55469. * Returns the GPU format for the given texture.
  55470. *
  55471. * @param {Texture} texture - The texture.
  55472. * @param {GPUDevice} [device] - The GPU device which is used for feature detection.
  55473. * @return {string} The GPU format.
  55474. */
  55475. function getFormat( texture, device ) {
  55476. const format = texture.format;
  55477. const type = texture.type;
  55478. const normalized = texture.normalized;
  55479. const colorSpace = texture.colorSpace;
  55480. const transfer = ColorManagement.getTransfer( colorSpace );
  55481. let formatGPU;
  55482. let textureFormatsTier1 = false;
  55483. if ( normalized ) {
  55484. textureFormatsTier1 = device.features.has( GPUFeatureName.TextureFormatsTier1 );
  55485. if ( textureFormatsTier1 === false ) {
  55486. warn( 'WebGPURenderer: Unable to use normalized textures without texture-formats-tier1 feature.' );
  55487. }
  55488. }
  55489. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  55490. switch ( format ) {
  55491. case RGB_S3TC_DXT1_Format:
  55492. case RGBA_S3TC_DXT1_Format:
  55493. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  55494. break;
  55495. case RGBA_S3TC_DXT3_Format:
  55496. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  55497. break;
  55498. case RGBA_S3TC_DXT5_Format:
  55499. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  55500. break;
  55501. case RED_RGTC1_Format:
  55502. formatGPU = GPUTextureFormat.BC4RUnorm;
  55503. break;
  55504. case SIGNED_RED_RGTC1_Format:
  55505. formatGPU = GPUTextureFormat.BC4RSnorm;
  55506. break;
  55507. case RED_GREEN_RGTC2_Format:
  55508. formatGPU = GPUTextureFormat.BC5RGUnorm;
  55509. break;
  55510. case SIGNED_RED_GREEN_RGTC2_Format:
  55511. formatGPU = GPUTextureFormat.BC5RGSnorm;
  55512. break;
  55513. case RGBA_BPTC_Format:
  55514. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC7RGBAUnormSRGB : GPUTextureFormat.BC7RGBAUnorm;
  55515. break;
  55516. case RGB_BPTC_SIGNED_Format:
  55517. formatGPU = GPUTextureFormat.BC6HRGBFloat;
  55518. break;
  55519. case RGB_BPTC_UNSIGNED_Format:
  55520. formatGPU = GPUTextureFormat.BC6HRGBUFloat;
  55521. break;
  55522. case RGB_ETC2_Format:
  55523. case RGB_ETC1_Format:
  55524. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  55525. break;
  55526. case RGBA_ETC2_EAC_Format:
  55527. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  55528. break;
  55529. case R11_EAC_Format:
  55530. formatGPU = GPUTextureFormat.EACR11Unorm;
  55531. break;
  55532. case SIGNED_R11_EAC_Format:
  55533. formatGPU = GPUTextureFormat.EACR11Snorm;
  55534. break;
  55535. case RG11_EAC_Format:
  55536. formatGPU = GPUTextureFormat.EACRG11Unorm;
  55537. break;
  55538. case SIGNED_RG11_EAC_Format:
  55539. formatGPU = GPUTextureFormat.EACRG11Snorm;
  55540. break;
  55541. case RGBA_ASTC_4x4_Format:
  55542. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  55543. break;
  55544. case RGBA_ASTC_5x4_Format:
  55545. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  55546. break;
  55547. case RGBA_ASTC_5x5_Format:
  55548. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  55549. break;
  55550. case RGBA_ASTC_6x5_Format:
  55551. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  55552. break;
  55553. case RGBA_ASTC_6x6_Format:
  55554. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  55555. break;
  55556. case RGBA_ASTC_8x5_Format:
  55557. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  55558. break;
  55559. case RGBA_ASTC_8x6_Format:
  55560. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  55561. break;
  55562. case RGBA_ASTC_8x8_Format:
  55563. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  55564. break;
  55565. case RGBA_ASTC_10x5_Format:
  55566. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  55567. break;
  55568. case RGBA_ASTC_10x6_Format:
  55569. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  55570. break;
  55571. case RGBA_ASTC_10x8_Format:
  55572. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  55573. break;
  55574. case RGBA_ASTC_10x10_Format:
  55575. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  55576. break;
  55577. case RGBA_ASTC_12x10_Format:
  55578. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  55579. break;
  55580. case RGBA_ASTC_12x12_Format:
  55581. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  55582. break;
  55583. case RGBAFormat:
  55584. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  55585. break;
  55586. default:
  55587. error( 'WebGPURenderer: Unsupported texture format.', format );
  55588. }
  55589. } else {
  55590. switch ( format ) {
  55591. case RGBAFormat:
  55592. switch ( type ) {
  55593. case ByteType:
  55594. formatGPU = GPUTextureFormat.RGBA8Snorm;
  55595. break;
  55596. case ShortType:
  55597. formatGPU = textureFormatsTier1 ? GPUTextureFormat.RGBA16Snorm : GPUTextureFormat.RGBA16Sint;
  55598. break;
  55599. case UnsignedShortType:
  55600. formatGPU = textureFormatsTier1 ? GPUTextureFormat.RGBA16Unorm : GPUTextureFormat.RGBA16Uint;
  55601. break;
  55602. case UnsignedIntType:
  55603. formatGPU = GPUTextureFormat.RGBA32Uint;
  55604. break;
  55605. case IntType:
  55606. formatGPU = GPUTextureFormat.RGBA32Sint;
  55607. break;
  55608. case UnsignedByteType:
  55609. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  55610. break;
  55611. case HalfFloatType:
  55612. formatGPU = GPUTextureFormat.RGBA16Float;
  55613. break;
  55614. case FloatType:
  55615. formatGPU = GPUTextureFormat.RGBA32Float;
  55616. break;
  55617. default:
  55618. error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  55619. }
  55620. break;
  55621. case RGBFormat:
  55622. switch ( type ) {
  55623. case UnsignedInt5999Type:
  55624. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  55625. break;
  55626. case UnsignedInt101111Type:
  55627. formatGPU = GPUTextureFormat.RG11B10UFloat;
  55628. break;
  55629. default:
  55630. error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  55631. }
  55632. break;
  55633. case RedFormat:
  55634. switch ( type ) {
  55635. case ByteType:
  55636. formatGPU = GPUTextureFormat.R8Snorm;
  55637. break;
  55638. case ShortType:
  55639. formatGPU = textureFormatsTier1 ? GPUTextureFormat.R16Snorm : GPUTextureFormat.R16Sint;
  55640. break;
  55641. case UnsignedShortType:
  55642. formatGPU = textureFormatsTier1 ? GPUTextureFormat.R16Unorm : GPUTextureFormat.R16Uint;
  55643. break;
  55644. case UnsignedIntType:
  55645. formatGPU = GPUTextureFormat.R32Uint;
  55646. break;
  55647. case IntType:
  55648. formatGPU = GPUTextureFormat.R32Sint;
  55649. break;
  55650. case UnsignedByteType:
  55651. formatGPU = GPUTextureFormat.R8Unorm;
  55652. break;
  55653. case HalfFloatType:
  55654. formatGPU = GPUTextureFormat.R16Float;
  55655. break;
  55656. case FloatType:
  55657. formatGPU = GPUTextureFormat.R32Float;
  55658. break;
  55659. default:
  55660. error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  55661. }
  55662. break;
  55663. case RGFormat:
  55664. switch ( type ) {
  55665. case ByteType:
  55666. formatGPU = GPUTextureFormat.RG8Snorm;
  55667. break;
  55668. case ShortType:
  55669. formatGPU = textureFormatsTier1 ? GPUTextureFormat.RG16Snorm : GPUTextureFormat.RG16Sint;
  55670. break;
  55671. case UnsignedShortType:
  55672. formatGPU = textureFormatsTier1 ? GPUTextureFormat.RG16Unorm : GPUTextureFormat.RG16Uint;
  55673. break;
  55674. case UnsignedIntType:
  55675. formatGPU = GPUTextureFormat.RG32Uint;
  55676. break;
  55677. case IntType:
  55678. formatGPU = GPUTextureFormat.RG32Sint;
  55679. break;
  55680. case UnsignedByteType:
  55681. formatGPU = GPUTextureFormat.RG8Unorm;
  55682. break;
  55683. case HalfFloatType:
  55684. formatGPU = GPUTextureFormat.RG16Float;
  55685. break;
  55686. case FloatType:
  55687. formatGPU = GPUTextureFormat.RG32Float;
  55688. break;
  55689. default:
  55690. error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  55691. }
  55692. break;
  55693. case DepthFormat:
  55694. switch ( type ) {
  55695. case UnsignedShortType:
  55696. formatGPU = GPUTextureFormat.Depth16Unorm;
  55697. break;
  55698. case UnsignedIntType:
  55699. formatGPU = GPUTextureFormat.Depth24Plus;
  55700. break;
  55701. case FloatType:
  55702. formatGPU = GPUTextureFormat.Depth32Float;
  55703. break;
  55704. default:
  55705. error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  55706. }
  55707. break;
  55708. case DepthStencilFormat:
  55709. switch ( type ) {
  55710. case UnsignedInt248Type:
  55711. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  55712. break;
  55713. case FloatType:
  55714. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  55715. error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  55716. }
  55717. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  55718. break;
  55719. default:
  55720. error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  55721. }
  55722. break;
  55723. case RedIntegerFormat:
  55724. switch ( type ) {
  55725. case IntType:
  55726. formatGPU = GPUTextureFormat.R32Sint;
  55727. break;
  55728. case UnsignedIntType:
  55729. formatGPU = GPUTextureFormat.R32Uint;
  55730. break;
  55731. default:
  55732. error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  55733. }
  55734. break;
  55735. case RGIntegerFormat:
  55736. switch ( type ) {
  55737. case IntType:
  55738. formatGPU = GPUTextureFormat.RG32Sint;
  55739. break;
  55740. case UnsignedIntType:
  55741. formatGPU = GPUTextureFormat.RG32Uint;
  55742. break;
  55743. default:
  55744. error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  55745. }
  55746. break;
  55747. case RGBAIntegerFormat:
  55748. switch ( type ) {
  55749. case IntType:
  55750. formatGPU = GPUTextureFormat.RGBA32Sint;
  55751. break;
  55752. case UnsignedIntType:
  55753. formatGPU = GPUTextureFormat.RGBA32Uint;
  55754. break;
  55755. default:
  55756. error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  55757. }
  55758. break;
  55759. default:
  55760. error( 'WebGPURenderer: Unsupported texture format.', format );
  55761. }
  55762. }
  55763. return formatGPU;
  55764. }
  55765. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  55766. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  55767. const wgslTypeLib$1 = {
  55768. 'f32': 'float',
  55769. 'i32': 'int',
  55770. 'u32': 'uint',
  55771. 'bool': 'bool',
  55772. 'vec2<f32>': 'vec2',
  55773. 'vec2<i32>': 'ivec2',
  55774. 'vec2<u32>': 'uvec2',
  55775. 'vec2<bool>': 'bvec2',
  55776. 'vec2f': 'vec2',
  55777. 'vec2i': 'ivec2',
  55778. 'vec2u': 'uvec2',
  55779. 'vec2b': 'bvec2',
  55780. 'vec3<f32>': 'vec3',
  55781. 'vec3<i32>': 'ivec3',
  55782. 'vec3<u32>': 'uvec3',
  55783. 'vec3<bool>': 'bvec3',
  55784. 'vec3f': 'vec3',
  55785. 'vec3i': 'ivec3',
  55786. 'vec3u': 'uvec3',
  55787. 'vec3b': 'bvec3',
  55788. 'vec4<f32>': 'vec4',
  55789. 'vec4<i32>': 'ivec4',
  55790. 'vec4<u32>': 'uvec4',
  55791. 'vec4<bool>': 'bvec4',
  55792. 'vec4f': 'vec4',
  55793. 'vec4i': 'ivec4',
  55794. 'vec4u': 'uvec4',
  55795. 'vec4b': 'bvec4',
  55796. 'mat2x2<f32>': 'mat2',
  55797. 'mat2x2f': 'mat2',
  55798. 'mat3x3<f32>': 'mat3',
  55799. 'mat3x3f': 'mat3',
  55800. 'mat4x4<f32>': 'mat4',
  55801. 'mat4x4f': 'mat4',
  55802. 'sampler': 'sampler',
  55803. 'texture_1d': 'texture',
  55804. 'texture_2d': 'texture',
  55805. 'texture_2d_array': 'texture',
  55806. 'texture_multisampled_2d': 'cubeTexture',
  55807. 'texture_depth_2d': 'depthTexture',
  55808. 'texture_depth_2d_array': 'depthTexture',
  55809. 'texture_depth_multisampled_2d': 'depthTexture',
  55810. 'texture_depth_cube': 'depthTexture',
  55811. 'texture_depth_cube_array': 'depthTexture',
  55812. 'texture_3d': 'texture3D',
  55813. 'texture_cube': 'cubeTexture',
  55814. 'texture_cube_array': 'cubeTexture',
  55815. 'texture_storage_1d': 'storageTexture',
  55816. 'texture_storage_2d': 'storageTexture',
  55817. 'texture_storage_2d_array': 'storageTexture',
  55818. 'texture_storage_3d': 'storageTexture'
  55819. };
  55820. const parse = ( source ) => {
  55821. source = source.trim();
  55822. const declaration = source.match( declarationRegexp );
  55823. if ( declaration !== null && declaration.length === 4 ) {
  55824. const inputsCode = declaration[ 2 ];
  55825. const propsMatches = [];
  55826. let match = null;
  55827. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  55828. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  55829. }
  55830. // Process matches to correctly pair names and types
  55831. const inputs = [];
  55832. for ( let i = 0; i < propsMatches.length; i ++ ) {
  55833. const { name, type } = propsMatches[ i ];
  55834. let resolvedType = type;
  55835. if ( resolvedType.startsWith( 'ptr' ) ) {
  55836. resolvedType = 'pointer';
  55837. } else {
  55838. if ( resolvedType.startsWith( 'texture' ) ) {
  55839. resolvedType = type.split( '<' )[ 0 ];
  55840. }
  55841. resolvedType = wgslTypeLib$1[ resolvedType ];
  55842. }
  55843. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  55844. }
  55845. const blockCode = source.substring( declaration[ 0 ].length );
  55846. const outputType = declaration[ 3 ] || 'void';
  55847. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  55848. const type = wgslTypeLib$1[ outputType ] || outputType;
  55849. return {
  55850. type,
  55851. inputs,
  55852. name,
  55853. inputsCode,
  55854. blockCode,
  55855. outputType
  55856. };
  55857. } else {
  55858. throw new Error( 'THREE.WGSLNodeFunction: Function is not a WGSL code.' );
  55859. }
  55860. };
  55861. /**
  55862. * This class represents a WSL node function.
  55863. *
  55864. * @augments NodeFunction
  55865. */
  55866. class WGSLNodeFunction extends NodeFunction {
  55867. /**
  55868. * Constructs a new WGSL node function.
  55869. *
  55870. * @param {string} source - The WGSL source.
  55871. */
  55872. constructor( source ) {
  55873. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  55874. super( type, inputs, name );
  55875. this.inputsCode = inputsCode;
  55876. this.blockCode = blockCode;
  55877. this.outputType = outputType;
  55878. }
  55879. /**
  55880. * This method returns the WGSL code of the node function.
  55881. *
  55882. * @param {string} [name=this.name] - The function's name.
  55883. * @return {string} The shader code.
  55884. */
  55885. getCode( name = this.name ) {
  55886. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  55887. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  55888. }
  55889. }
  55890. /**
  55891. * A WGSL node parser.
  55892. *
  55893. * @augments NodeParser
  55894. */
  55895. class WGSLNodeParser extends NodeParser {
  55896. /**
  55897. * The method parses the given WGSL code an returns a node function.
  55898. *
  55899. * @param {string} source - The WGSL code.
  55900. * @return {WGSLNodeFunction} A node function.
  55901. */
  55902. parseFunction( source ) {
  55903. return new WGSLNodeFunction( source );
  55904. }
  55905. }
  55906. const accessNames = {
  55907. [ NodeAccess.READ_ONLY ]: 'read',
  55908. [ NodeAccess.WRITE_ONLY ]: 'write',
  55909. [ NodeAccess.READ_WRITE ]: 'read_write'
  55910. };
  55911. const wrapNames = {
  55912. [ RepeatWrapping ]: 'repeat',
  55913. [ ClampToEdgeWrapping ]: 'clamp',
  55914. [ MirroredRepeatWrapping ]: 'mirror'
  55915. };
  55916. const gpuShaderStageLib = {
  55917. 'vertex': GPUShaderStage.VERTEX,
  55918. 'fragment': GPUShaderStage.FRAGMENT,
  55919. 'compute': GPUShaderStage.COMPUTE
  55920. };
  55921. const supports = {
  55922. instance: true,
  55923. swizzleAssign: false,
  55924. storageBuffer: true
  55925. };
  55926. const wgslFnOpLib = {
  55927. '^^': 'tsl_xor'
  55928. };
  55929. const wgslTypeLib = {
  55930. float: 'f32',
  55931. int: 'i32',
  55932. uint: 'u32',
  55933. bool: 'bool',
  55934. color: 'vec3<f32>',
  55935. vec2: 'vec2<f32>',
  55936. ivec2: 'vec2<i32>',
  55937. uvec2: 'vec2<u32>',
  55938. bvec2: 'vec2<bool>',
  55939. vec3: 'vec3<f32>',
  55940. ivec3: 'vec3<i32>',
  55941. uvec3: 'vec3<u32>',
  55942. bvec3: 'vec3<bool>',
  55943. vec4: 'vec4<f32>',
  55944. ivec4: 'vec4<i32>',
  55945. uvec4: 'vec4<u32>',
  55946. bvec4: 'vec4<bool>',
  55947. mat2: 'mat2x2<f32>',
  55948. mat3: 'mat3x3<f32>',
  55949. mat4: 'mat4x4<f32>'
  55950. };
  55951. const wgslCodeCache = {};
  55952. const wgslPolyfill = {
  55953. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  55954. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  55955. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  55956. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  55957. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  55958. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  55959. 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 ); }' ),
  55960. 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 ); }' ),
  55961. 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 ); }' ),
  55962. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  55963. 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 ); }' ),
  55964. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  55965. inverse_mat2: new CodeNode( /* wgsl */`
  55966. fn tsl_inverse_mat2( m : mat2x2<f32> ) -> mat2x2<f32> {
  55967. let det = m[ 0 ][ 0 ] * m[ 1 ][ 1 ] - m[ 0 ][ 1 ] * m[ 1 ][ 0 ];
  55968. return mat2x2<f32>(
  55969. m[ 1 ][ 1 ], - m[ 0 ][ 1 ],
  55970. - m[ 1 ][ 0 ], m[ 0 ][ 0 ]
  55971. ) * ( 1.0 / det );
  55972. }
  55973. ` ),
  55974. inverse_mat3: new CodeNode( /* wgsl */`
  55975. fn tsl_inverse_mat3( m : mat3x3<f32> ) -> mat3x3<f32> {
  55976. let a00 = m[ 0 ][ 0 ]; let a01 = m[ 0 ][ 1 ]; let a02 = m[ 0 ][ 2 ];
  55977. let a10 = m[ 1 ][ 0 ]; let a11 = m[ 1 ][ 1 ]; let a12 = m[ 1 ][ 2 ];
  55978. let a20 = m[ 2 ][ 0 ]; let a21 = m[ 2 ][ 1 ]; let a22 = m[ 2 ][ 2 ];
  55979. let b01 = a22 * a11 - a12 * a21;
  55980. let b11 = - a22 * a10 + a12 * a20;
  55981. let b21 = a21 * a10 - a11 * a20;
  55982. let det = a00 * b01 + a01 * b11 + a02 * b21;
  55983. return mat3x3<f32>(
  55984. b01, ( - a22 * a01 + a02 * a21 ), ( a12 * a01 - a02 * a11 ),
  55985. b11, ( a22 * a00 - a02 * a20 ), ( - a12 * a00 + a02 * a10 ),
  55986. b21, ( - a21 * a00 + a01 * a20 ), ( a11 * a00 - a01 * a10 )
  55987. ) * ( 1.0 / det );
  55988. }
  55989. ` ),
  55990. inverse_mat4: new CodeNode( /* wgsl */`
  55991. fn tsl_inverse_mat4( m : mat4x4<f32> ) -> mat4x4<f32> {
  55992. let a00 = m[ 0 ][ 0 ]; let a01 = m[ 0 ][ 1 ]; let a02 = m[ 0 ][ 2 ]; let a03 = m[ 0 ][ 3 ];
  55993. let a10 = m[ 1 ][ 0 ]; let a11 = m[ 1 ][ 1 ]; let a12 = m[ 1 ][ 2 ]; let a13 = m[ 1 ][ 3 ];
  55994. let a20 = m[ 2 ][ 0 ]; let a21 = m[ 2 ][ 1 ]; let a22 = m[ 2 ][ 2 ]; let a23 = m[ 2 ][ 3 ];
  55995. let a30 = m[ 3 ][ 0 ]; let a31 = m[ 3 ][ 1 ]; let a32 = m[ 3 ][ 2 ]; let a33 = m[ 3 ][ 3 ];
  55996. let b00 = a00 * a11 - a01 * a10;
  55997. let b01 = a00 * a12 - a02 * a10;
  55998. let b02 = a00 * a13 - a03 * a10;
  55999. let b03 = a01 * a12 - a02 * a11;
  56000. let b04 = a01 * a13 - a03 * a11;
  56001. let b05 = a02 * a13 - a03 * a12;
  56002. let b06 = a20 * a31 - a21 * a30;
  56003. let b07 = a20 * a32 - a22 * a30;
  56004. let b08 = a20 * a33 - a23 * a30;
  56005. let b09 = a21 * a32 - a22 * a31;
  56006. let b10 = a21 * a33 - a23 * a31;
  56007. let b11 = a22 * a33 - a23 * a32;
  56008. let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  56009. return mat4x4<f32>(
  56010. a11 * b11 - a12 * b10 + a13 * b09,
  56011. a02 * b10 - a01 * b11 - a03 * b09,
  56012. a31 * b05 - a32 * b04 + a33 * b03,
  56013. a22 * b04 - a21 * b05 - a23 * b03,
  56014. a12 * b08 - a10 * b11 - a13 * b07,
  56015. a00 * b11 - a02 * b08 + a03 * b07,
  56016. a32 * b02 - a30 * b05 - a33 * b01,
  56017. a20 * b05 - a22 * b02 + a23 * b01,
  56018. a10 * b10 - a11 * b08 + a13 * b06,
  56019. a01 * b08 - a00 * b10 - a03 * b06,
  56020. a30 * b04 - a31 * b02 + a33 * b00,
  56021. a21 * b02 - a20 * b04 - a23 * b00,
  56022. a11 * b07 - a10 * b09 - a12 * b06,
  56023. a00 * b09 - a01 * b07 + a02 * b06,
  56024. a31 * b01 - a30 * b03 - a32 * b00,
  56025. a20 * b03 - a21 * b01 + a22 * b00
  56026. ) * ( 1.0 / det );
  56027. }
  56028. ` ),
  56029. biquadraticTexture: new CodeNode( /* wgsl */`
  56030. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  56031. let res = vec2f( iRes );
  56032. let uvScaled = coord * res;
  56033. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  56034. // https://www.shadertoy.com/view/WtyXRy
  56035. let uv = uvWrapping - 0.5;
  56036. let iuv = floor( uv );
  56037. let f = fract( uv );
  56038. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  56039. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  56040. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  56041. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  56042. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  56043. }
  56044. ` ),
  56045. biquadraticTextureArray: new CodeNode( /* wgsl */`
  56046. fn tsl_biquadraticTexture_array( map : texture_2d_array<f32>, coord : vec2f, iRes : vec2u, layer : u32, level : u32 ) -> vec4f {
  56047. let res = vec2f( iRes );
  56048. let uvScaled = coord * res;
  56049. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  56050. // https://www.shadertoy.com/view/WtyXRy
  56051. let uv = uvWrapping - 0.5;
  56052. let iuv = floor( uv );
  56053. let f = fract( uv );
  56054. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, layer, level );
  56055. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, layer, level );
  56056. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, layer, level );
  56057. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, layer, level );
  56058. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  56059. }
  56060. ` )
  56061. };
  56062. const wgslMethods = {
  56063. dFdx: 'dpdx',
  56064. dFdy: '- dpdy',
  56065. mod_float: 'tsl_mod_float',
  56066. mod_vec2: 'tsl_mod_vec2',
  56067. mod_vec3: 'tsl_mod_vec3',
  56068. mod_vec4: 'tsl_mod_vec4',
  56069. equals_bool: 'tsl_equals_bool',
  56070. equals_bvec2: 'tsl_equals_bvec2',
  56071. equals_bvec3: 'tsl_equals_bvec3',
  56072. equals_bvec4: 'tsl_equals_bvec4',
  56073. inverse_mat2: 'tsl_inverse_mat2',
  56074. inverse_mat3: 'tsl_inverse_mat3',
  56075. inverse_mat4: 'tsl_inverse_mat4',
  56076. inversesqrt: 'inverseSqrt',
  56077. bitcast: 'bitcast<f32>',
  56078. floatpack_snorm_2x16: 'pack2x16snorm',
  56079. floatpack_unorm_2x16: 'pack2x16unorm',
  56080. floatpack_float16_2x16: 'pack2x16float',
  56081. floatunpack_snorm_2x16: 'unpack2x16snorm',
  56082. floatunpack_unorm_2x16: 'unpack2x16unorm',
  56083. floatunpack_float16_2x16: 'unpack2x16float'
  56084. };
  56085. // See: https://www.w3.org/TR/WGSL/#keyword-summary and #reserved-words-section
  56086. const wgslReservedKeywords = new Set( [
  56087. // keywords
  56088. 'alias', 'break', 'case', 'const', 'const_assert', 'continue', 'continuing', 'default', 'diagnostic',
  56089. 'discard', 'else', 'enable', 'false', 'fn', 'for', 'if', 'let', 'loop', 'override', 'requires',
  56090. 'return', 'struct', 'switch', 'true', 'var', 'while',
  56091. // reserved words
  56092. 'NULL', 'Self', 'abstract', 'active', 'alignas', 'alignof', 'as', 'asm', 'asm_fragment', 'async',
  56093. 'attribute', 'auto', 'await', 'become', 'binding_array', 'cast', 'catch', 'class', 'co_await',
  56094. 'co_return', 'co_yield', 'coherent', 'column_major', 'common', 'compile', 'compile_fragment',
  56095. 'concept', 'const_cast', 'consteval', 'constexpr', 'constinit', 'crate', 'debugger', 'decltype',
  56096. 'delete', 'demote', 'demote_to_helper', 'do', 'dynamic_cast', 'enum', 'explicit', 'export',
  56097. 'extends', 'extern', 'external', 'fallthrough', 'filter', 'final', 'finally', 'friend', 'from',
  56098. 'fxgroup', 'get', 'goto', 'groupshared', 'highp', 'impl', 'implements', 'import', 'inline',
  56099. 'instanceof', 'interface', 'layout', 'lowp', 'macro', 'macro_rules', 'match', 'mediump', 'meta',
  56100. 'mod', 'module', 'move', 'mut', 'mutable', 'namespace', 'new', 'nil', 'noexcept', 'noinline',
  56101. 'nointerpolation', 'non_coherent', 'noncoherent', 'noperspective', 'null', 'nullptr', 'of',
  56102. 'operator', 'package', 'packoffset', 'partition', 'pass', 'patch', 'pixelfragment', 'precise',
  56103. 'precision', 'premerge', 'priv', 'protected', 'pub', 'public', 'readonly', 'ref', 'regardless',
  56104. 'register', 'reinterpret_cast', 'require', 'resource', 'restrict', 'self', 'set', 'shared',
  56105. 'sizeof', 'smooth', 'snorm', 'static', 'static_assert', 'static_cast', 'std', 'subroutine',
  56106. 'super', 'target', 'template', 'this', 'thread_local', 'throw', 'trait', 'try', 'type', 'typedef',
  56107. 'typeid', 'typename', 'typeof', 'union', 'unless', 'unorm', 'unsafe', 'unsized', 'use', 'using',
  56108. 'varying', 'virtual', 'volatile', 'wgsl', 'where', 'with', 'writeonly', 'yield',
  56109. // generated entry points
  56110. 'main'
  56111. ] );
  56112. //
  56113. let diagnostics = '';
  56114. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  56115. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  56116. }
  56117. /**
  56118. * A node builder targeting WGSL.
  56119. *
  56120. * This module generates WGSL shader code from node materials and also
  56121. * generates the respective bindings and vertex buffer definitions. These
  56122. * data are later used by the renderer to create render and compute pipelines
  56123. * for render objects.
  56124. *
  56125. * @augments NodeBuilder
  56126. */
  56127. class WGSLNodeBuilder extends NodeBuilder {
  56128. /**
  56129. * Constructs a new WGSL node builder renderer.
  56130. *
  56131. * @param {Object3D} object - The 3D object.
  56132. * @param {Renderer} renderer - The renderer.
  56133. */
  56134. constructor( object, renderer ) {
  56135. super( object, renderer, new WGSLNodeParser() );
  56136. /**
  56137. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  56138. * another dictionary which manages UBOs per group ('render','frame','object').
  56139. *
  56140. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  56141. */
  56142. this.uniformGroups = {};
  56143. /**
  56144. * A dictionary that holds the assigned binding indices for each uniform group.
  56145. * This ensures the same binding index is used across all shader stages.
  56146. *
  56147. * @type {Object<string,{index: number, id: number}>}
  56148. */
  56149. this.uniformGroupsBindings = {};
  56150. /**
  56151. * A dictionary that holds for each shader stage a Map of builtins.
  56152. *
  56153. * @type {Object<string,Map<string,Object>>}
  56154. */
  56155. this.builtins = {};
  56156. /**
  56157. * A dictionary that holds for each shader stage a Set of directives.
  56158. *
  56159. * @type {Object<string,Set<string>>}
  56160. */
  56161. this.directives = {};
  56162. /**
  56163. * A map for managing scope arrays. Only relevant for when using
  56164. * {@link WorkgroupInfoNode} in context of compute shaders.
  56165. *
  56166. * @type {Map<string,Object>}
  56167. */
  56168. this.scopedArrays = new Map();
  56169. /**
  56170. * A flag that indicates that early returns are allowed.
  56171. *
  56172. * @type {boolean}
  56173. * @default true
  56174. */
  56175. this.allowEarlyReturns = true;
  56176. /**
  56177. * A flag that indicates that global variables are allowed.
  56178. *
  56179. * @type {boolean}
  56180. * @default true
  56181. */
  56182. this.allowGlobalVariables = true;
  56183. }
  56184. /**
  56185. * Generates the WGSL snippet for sampled textures.
  56186. *
  56187. * @private
  56188. * @param {Texture} texture - The texture.
  56189. * @param {string} textureProperty - The name of the texture uniform in the shader.
  56190. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  56191. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  56192. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  56193. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  56194. * @return {string} The WGSL snippet.
  56195. */
  56196. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  56197. if ( shaderStage === 'fragment' ) {
  56198. if ( depthSnippet ) {
  56199. if ( offsetSnippet ) {
  56200. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ offsetSnippet } )`;
  56201. }
  56202. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  56203. } else {
  56204. if ( offsetSnippet ) {
  56205. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ offsetSnippet } )`;
  56206. }
  56207. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  56208. }
  56209. } else {
  56210. return this.generateTextureSampleLevel( texture, textureProperty, uvSnippet, '0', depthSnippet );
  56211. }
  56212. }
  56213. /**
  56214. * Generates the WGSL snippet when sampling textures with explicit mip level.
  56215. *
  56216. * @private
  56217. * @param {Texture} texture - The texture.
  56218. * @param {string} textureProperty - The name of the texture uniform in the shader.
  56219. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  56220. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  56221. * @param {string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  56222. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  56223. * @return {string} The WGSL snippet.
  56224. */
  56225. generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  56226. if ( this.isUnfilterable( texture ) === false ) {
  56227. if ( depthSnippet ) {
  56228. if ( offsetSnippet ) {
  56229. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  56230. }
  56231. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ levelSnippet } )`;
  56232. } else {
  56233. if ( offsetSnippet ) {
  56234. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  56235. }
  56236. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  56237. }
  56238. } else if ( this.isFilteredTexture( texture ) ) {
  56239. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet, depthSnippet );
  56240. } else {
  56241. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  56242. }
  56243. }
  56244. /**
  56245. * Generates a wrap function used in context of textures.
  56246. *
  56247. * @param {Texture} texture - The texture to generate the function for.
  56248. * @return {string} The name of the generated function.
  56249. */
  56250. generateWrapFunction( texture ) {
  56251. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }T_${ texture.is3DTexture || texture.isData3DTexture ? '3d' : '2d' }`;
  56252. let nodeCode = wgslCodeCache[ functionName ];
  56253. if ( nodeCode === undefined ) {
  56254. const includes = [];
  56255. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  56256. const coordType = texture.is3DTexture || texture.isData3DTexture ? 'vec3f' : 'vec2f';
  56257. let code = `fn ${ functionName }( coord : ${ coordType } ) -> ${ coordType } {\n\n\treturn ${ coordType }(\n`;
  56258. const addWrapSnippet = ( wrap, axis ) => {
  56259. if ( wrap === RepeatWrapping ) {
  56260. includes.push( wgslPolyfill.repeatWrapping_float );
  56261. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  56262. } else if ( wrap === ClampToEdgeWrapping ) {
  56263. includes.push( wgslPolyfill.clampWrapping_float );
  56264. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  56265. } else if ( wrap === MirroredRepeatWrapping ) {
  56266. includes.push( wgslPolyfill.mirrorWrapping_float );
  56267. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  56268. } else {
  56269. code += `\t\tcoord.${ axis }`;
  56270. warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  56271. }
  56272. };
  56273. addWrapSnippet( texture.wrapS, 'x' );
  56274. code += ',\n';
  56275. addWrapSnippet( texture.wrapT, 'y' );
  56276. if ( texture.is3DTexture || texture.isData3DTexture ) {
  56277. code += ',\n';
  56278. addWrapSnippet( texture.wrapR, 'z' );
  56279. }
  56280. code += '\n\t);\n\n}\n';
  56281. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  56282. }
  56283. nodeCode.build( this );
  56284. return functionName;
  56285. }
  56286. /**
  56287. * Generates the array declaration string.
  56288. *
  56289. * @param {string} type - The type.
  56290. * @param {?number} [count] - The count.
  56291. * @return {string} The generated value as a shader string.
  56292. */
  56293. generateArrayDeclaration( type, count ) {
  56294. return `array< ${ this.getType( type ) }, ${ count } >`;
  56295. }
  56296. /**
  56297. * Generates a WGSL variable that holds the texture dimension of the given texture.
  56298. * It also returns information about the number of layers (elements) of an arrayed
  56299. * texture as well as the cube face count of cube textures.
  56300. *
  56301. * @param {Texture} texture - The texture to generate the function for.
  56302. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  56303. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  56304. * @return {string} The name of the dimension variable.
  56305. */
  56306. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  56307. const textureData = this.getDataFromNode( texture, this.shaderStage, this.cache );
  56308. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  56309. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  56310. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  56311. let textureDimensionsParams;
  56312. let dimensionType;
  56313. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  56314. const isMultisampled = primarySamples > 1;
  56315. if ( texture.is3DTexture || texture.isData3DTexture ) {
  56316. dimensionType = 'vec3<u32>';
  56317. } else {
  56318. // Regular 2D textures, depth textures, etc.
  56319. dimensionType = 'vec2<u32>';
  56320. }
  56321. // Build parameters string based on texture type and multisampling
  56322. if ( isMultisampled || texture.isStorageTexture ) {
  56323. textureDimensionsParams = textureProperty;
  56324. } else {
  56325. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  56326. }
  56327. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  56328. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  56329. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.is3DTexture || texture.isData3DTexture ) {
  56330. textureData.arrayLayerCount = new VarNode(
  56331. new ExpressionNode(
  56332. `textureNumLayers(${textureProperty})`,
  56333. 'u32'
  56334. )
  56335. );
  56336. }
  56337. // For cube textures, we know it's always 6 faces
  56338. if ( texture.isTextureCube ) {
  56339. textureData.cubeFaceCount = new VarNode(
  56340. new ExpressionNode( '6u', 'u32' )
  56341. );
  56342. }
  56343. }
  56344. return textureDimensionNode.build( this );
  56345. }
  56346. /**
  56347. * Generates the WGSL snippet that resolves the dimensions of the given texture.
  56348. *
  56349. * @param {Texture} texture - The texture.
  56350. * @param {string} textureProperty - The name of the texture uniform in the shader.
  56351. * @param {string} levelSnippet - A WGSL snippet that represents the mip level.
  56352. * @return {string} The WGSL snippet.
  56353. */
  56354. generateTextureSize( texture, textureProperty, levelSnippet ) {
  56355. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  56356. const isMultisampled = primarySamples > 1;
  56357. const params = ( isMultisampled || texture.isStorageTexture ) ? textureProperty : `${ textureProperty }, ${ levelSnippet }`;
  56358. return `textureDimensions( ${ params } )`;
  56359. }
  56360. /**
  56361. * Generates the WGSL snippet for a manual filtered texture.
  56362. *
  56363. * @param {Texture} texture - The texture.
  56364. * @param {string} textureProperty - The name of the texture uniform in the shader.
  56365. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  56366. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  56367. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  56368. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  56369. * @return {string} The WGSL snippet.
  56370. */
  56371. generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet = '0u', depthSnippet ) {
  56372. const wrapFunction = this.generateWrapFunction( texture );
  56373. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  56374. if ( offsetSnippet ) {
  56375. uvSnippet = `${ uvSnippet } + vec2<f32>(${ offsetSnippet }) / ${ textureDimension }`;
  56376. }
  56377. if ( depthSnippet ) {
  56378. this._include( 'biquadraticTextureArray' );
  56379. return `tsl_biquadraticTexture_array( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ depthSnippet } ), u32( ${ levelSnippet } ) )`;
  56380. }
  56381. this._include( 'biquadraticTexture' );
  56382. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  56383. }
  56384. /**
  56385. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  56386. * Since it's a lookup, no sampling or filtering is applied.
  56387. *
  56388. * @param {Texture} texture - The texture.
  56389. * @param {string} textureProperty - The name of the texture uniform in the shader.
  56390. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  56391. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  56392. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  56393. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  56394. * @return {string} The WGSL snippet.
  56395. */
  56396. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet = '0u' ) {
  56397. // Cube textures cannot use textureLoad in WGSL, must use textureSampleLevel
  56398. if ( texture.isCubeTexture === true ) {
  56399. if ( offsetSnippet ) {
  56400. uvSnippet = `${ uvSnippet } + vec3<f32>(${ offsetSnippet })`;
  56401. }
  56402. // Depth textures require integer level, regular textures use float
  56403. const levelType = texture.isDepthTexture ? 'u32' : 'f32';
  56404. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelType }( ${ levelSnippet } ) )`;
  56405. }
  56406. const wrapFunction = this.generateWrapFunction( texture );
  56407. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  56408. const vecType = texture.is3DTexture || texture.isData3DTexture ? 'vec3' : 'vec2';
  56409. const textureDimensionMargin = ( vecType === 'vec3' ) ? 'vec3<u32>( 1, 1, 1 )' : 'vec2<u32>( 1, 1 )';
  56410. if ( offsetSnippet ) {
  56411. uvSnippet = `${ uvSnippet } + ${ vecType }<f32>(${ offsetSnippet }) / ${ vecType }<f32>( ${ textureDimension } )`;
  56412. }
  56413. const clampMin = `${ vecType }<f32>( 0 )`;
  56414. const clampMax = `${ vecType }<f32>( ${ textureDimension } - ${ textureDimensionMargin } )`;
  56415. uvSnippet = `${ vecType }<u32>( clamp( floor( ${ wrapFunction }( ${ uvSnippet } ) * ${ vecType }<f32>( ${ textureDimension } ) ), ${ clampMin }, ${ clampMax } ) )`;
  56416. return this.generateTextureLoad( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, null );
  56417. }
  56418. /**
  56419. * Generates the WGSL snippet that reads a single texel from a storage texture.
  56420. *
  56421. * @param {Texture} texture - The texture.
  56422. * @param {string} textureProperty - The name of the texture uniform in the shader.
  56423. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  56424. * @param {?string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  56425. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  56426. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  56427. * @return {string} The WGSL snippet.
  56428. */
  56429. generateStorageTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  56430. if ( offsetSnippet ) {
  56431. uvIndexSnippet = `${ uvIndexSnippet } + ${ offsetSnippet }`;
  56432. }
  56433. let snippet;
  56434. if ( depthSnippet ) {
  56435. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet } )`;
  56436. } else {
  56437. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet } )`;
  56438. }
  56439. return snippet;
  56440. }
  56441. /**
  56442. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  56443. *
  56444. * @param {Texture} texture - The texture.
  56445. * @param {string} textureProperty - The name of the texture uniform in the shader.
  56446. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  56447. * @param {?string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  56448. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  56449. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  56450. * @return {string} The WGSL snippet.
  56451. */
  56452. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  56453. if ( levelSnippet === null ) levelSnippet = '0u';
  56454. if ( offsetSnippet ) {
  56455. uvIndexSnippet = `${ uvIndexSnippet } + ${ offsetSnippet }`;
  56456. }
  56457. let snippet;
  56458. if ( depthSnippet ) {
  56459. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  56460. } else {
  56461. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  56462. if ( this.renderer.backend.compatibilityMode && texture.isDepthTexture ) {
  56463. snippet += '.x';
  56464. }
  56465. }
  56466. return snippet;
  56467. }
  56468. /**
  56469. * Generates the WGSL snippet that writes a single texel to a texture.
  56470. *
  56471. * @param {Texture} texture - The texture.
  56472. * @param {string} textureProperty - The name of the texture uniform in the shader.
  56473. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  56474. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  56475. * @param {string} valueSnippet - A WGSL snippet that represent the new texel value.
  56476. * @return {string} The WGSL snippet.
  56477. */
  56478. generateTextureStore( texture, textureProperty, uvIndexSnippet, depthSnippet, valueSnippet ) {
  56479. let snippet;
  56480. if ( depthSnippet ) {
  56481. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ valueSnippet } )`;
  56482. } else {
  56483. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  56484. }
  56485. return snippet;
  56486. }
  56487. /**
  56488. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  56489. *
  56490. * @param {Texture} texture - The texture.
  56491. * @return {boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  56492. */
  56493. isSampleCompare( texture ) {
  56494. return texture.isDepthTexture === true && texture.compareFunction !== null && this.renderer.hasCompatibility( Compatibility.TEXTURE_COMPARE );
  56495. }
  56496. /**
  56497. * Returns `true` if the given texture is unfilterable.
  56498. *
  56499. * @param {Texture} texture - The texture.
  56500. * @return {boolean} Whether the given texture is unfilterable or not.
  56501. */
  56502. isUnfilterable( texture ) {
  56503. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  56504. ( ! this.isAvailable( 'float32Filterable' ) && texture.type === FloatType ) ||
  56505. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  56506. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1 ||
  56507. texture.normalized === true && ( texture.type === ShortType || texture.type === UnsignedShortType );
  56508. }
  56509. /**
  56510. * Generates the WGSL snippet for sampling/loading the given texture.
  56511. *
  56512. * @param {Texture} texture - The texture.
  56513. * @param {string} textureProperty - The name of the texture uniform in the shader.
  56514. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  56515. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  56516. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  56517. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  56518. * @return {string} The WGSL snippet.
  56519. */
  56520. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  56521. let snippet = null;
  56522. if ( this.isUnfilterable( texture ) ) {
  56523. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, '0', shaderStage );
  56524. } else {
  56525. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage );
  56526. }
  56527. return snippet;
  56528. }
  56529. /**
  56530. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  56531. *
  56532. * @param {Texture} texture - The texture.
  56533. * @param {string} textureProperty - The name of the texture uniform in the shader.
  56534. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  56535. * @param {Array<string>} gradSnippet - An array holding both gradient WGSL snippets.
  56536. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  56537. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  56538. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  56539. * @return {string} The WGSL snippet.
  56540. */
  56541. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  56542. if ( shaderStage === 'fragment' ) {
  56543. if ( depthSnippet ) {
  56544. if ( offsetSnippet ) {
  56545. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  56546. }
  56547. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  56548. } else {
  56549. if ( offsetSnippet ) {
  56550. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  56551. }
  56552. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  56553. }
  56554. } else {
  56555. error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  56556. }
  56557. }
  56558. /**
  56559. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  56560. * against a reference value.
  56561. *
  56562. * @param {Texture} texture - The texture.
  56563. * @param {string} textureProperty - The name of the texture uniform in the shader.
  56564. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  56565. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  56566. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  56567. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  56568. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  56569. * @return {string} The WGSL snippet.
  56570. */
  56571. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  56572. if ( shaderStage === 'fragment' ) {
  56573. if ( texture.isDepthTexture === true && texture.isArrayTexture === true ) {
  56574. if ( offsetSnippet ) {
  56575. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  56576. }
  56577. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } )`;
  56578. }
  56579. if ( offsetSnippet ) {
  56580. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  56581. }
  56582. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  56583. } else {
  56584. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  56585. }
  56586. }
  56587. /**
  56588. * Generates the WGSL snippet for gathering four texels from the given texture.
  56589. *
  56590. * @param {Texture} texture - The texture.
  56591. * @param {string} textureProperty - The name of the texture uniform in the shader.
  56592. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  56593. * @param {string} gatherSnippet - A WGSL snippet that represents the index of the channel to read.
  56594. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  56595. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  56596. * @param {?string} flipYSnippet - A WGSL snippet that represents the y-flip. Only used for WebGL.
  56597. * @return {string} The WGSL snippet.
  56598. */
  56599. generateTextureGather( texture, textureProperty, uvSnippet, gatherSnippet, depthSnippet, offsetSnippet ) {
  56600. const componentSnippet = texture.isDepthTexture === true ? '' : `${gatherSnippet}, `;
  56601. if ( depthSnippet ) {
  56602. if ( offsetSnippet ) {
  56603. return `textureGather( ${componentSnippet}${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ offsetSnippet } )`;
  56604. }
  56605. return `textureGather( ${componentSnippet}${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  56606. }
  56607. if ( offsetSnippet ) {
  56608. return `textureGather( ${componentSnippet}${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ offsetSnippet } )`;
  56609. }
  56610. return `textureGather( ${componentSnippet}${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet })`;
  56611. }
  56612. /**
  56613. * Generates the WGSL snippet for performing a depth comparison on four texels in the given depth texture.
  56614. *
  56615. * @param {Texture} texture - The texture.
  56616. * @param {string} textureProperty - The name of the texture uniform in the shader.
  56617. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  56618. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  56619. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  56620. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  56621. * @param {?string} flipYSnippet - A WGSL snippet that represents the y-flip. Only used for WebGL.
  56622. * @return {string} The WGSL snippet.
  56623. */
  56624. generateTextureGatherCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet ) {
  56625. if ( depthSnippet ) {
  56626. if ( offsetSnippet ) {
  56627. return `textureGatherCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  56628. }
  56629. return `textureGatherCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet })`;
  56630. }
  56631. if ( offsetSnippet ) {
  56632. return `textureGatherCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  56633. }
  56634. return `textureGatherCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet })`;
  56635. }
  56636. /**
  56637. * Generates the WGSL snippet when sampling textures with explicit mip level.
  56638. *
  56639. * @param {Texture} texture - The texture.
  56640. * @param {string} textureProperty - The name of the texture uniform in the shader.
  56641. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  56642. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  56643. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  56644. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  56645. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  56646. * @return {string} The WGSL snippet.
  56647. */
  56648. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  56649. if ( this.isUnfilterable( texture ) === false ) {
  56650. if ( depthSnippet ) {
  56651. if ( offsetSnippet ) {
  56652. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  56653. }
  56654. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ levelSnippet } )`;
  56655. } else {
  56656. if ( offsetSnippet ) {
  56657. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  56658. }
  56659. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  56660. }
  56661. } else if ( this.isFilteredTexture( texture ) ) {
  56662. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet, depthSnippet );
  56663. } else {
  56664. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  56665. }
  56666. }
  56667. /**
  56668. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  56669. *
  56670. * @param {Texture} texture - The texture.
  56671. * @param {string} textureProperty - The name of the texture uniform in the shader.
  56672. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  56673. * @param {string} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  56674. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  56675. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  56676. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  56677. * @return {string} The WGSL snippet.
  56678. */
  56679. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  56680. if ( shaderStage === 'fragment' ) {
  56681. if ( depthSnippet ) {
  56682. if ( offsetSnippet ) {
  56683. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ biasSnippet }, ${ offsetSnippet } )`;
  56684. }
  56685. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ biasSnippet } )`;
  56686. } else {
  56687. if ( offsetSnippet ) {
  56688. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet }, ${ offsetSnippet } )`;
  56689. }
  56690. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  56691. }
  56692. } else {
  56693. error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  56694. }
  56695. }
  56696. /**
  56697. * Returns a WGSL snippet that represents the property name of the given node.
  56698. *
  56699. * @param {Node} node - The node.
  56700. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  56701. * @return {string} The property name.
  56702. */
  56703. getPropertyName( node, shaderStage = this.shaderStage ) {
  56704. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  56705. if ( shaderStage === 'vertex' ) {
  56706. return `varyings.${ node.name }`;
  56707. }
  56708. } else if ( node.isNodeUniform === true ) {
  56709. const name = node.name;
  56710. const type = node.type;
  56711. if ( type === 'texture' || type === 'cubeTexture' || type === 'cubeDepthTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  56712. return name;
  56713. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  56714. if ( this.isCustomStruct( node ) ) {
  56715. return name;
  56716. }
  56717. return name + '.value';
  56718. } else {
  56719. return node.groupNode.name + '.' + name;
  56720. }
  56721. }
  56722. return super.getPropertyName( node );
  56723. }
  56724. /**
  56725. * Returns whether the given name is a reserved keyword of WGSL.
  56726. *
  56727. * @param {string} name - The name to test.
  56728. * @return {boolean} Whether the name is a reserved keyword or not.
  56729. */
  56730. isReservedKeyword( name ) {
  56731. return wgslReservedKeywords.has( name );
  56732. }
  56733. /**
  56734. * Returns the output struct name.
  56735. *
  56736. * @return {string} The name of the output struct.
  56737. */
  56738. getOutputStructName() {
  56739. return 'output';
  56740. }
  56741. /**
  56742. * Returns the native shader operator name for a given generic name.
  56743. *
  56744. * @param {string} op - The operator name to resolve.
  56745. * @return {?string} The resolved operator name.
  56746. */
  56747. getFunctionOperator( op ) {
  56748. const fnOp = wgslFnOpLib[ op ];
  56749. if ( fnOp !== undefined ) {
  56750. this._include( fnOp );
  56751. return fnOp;
  56752. }
  56753. return null;
  56754. }
  56755. /**
  56756. * Returns the node access for the given node and shader stage.
  56757. *
  56758. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  56759. * @param {string} shaderStage - The shader stage.
  56760. * @return {string} The node access.
  56761. */
  56762. getNodeAccess( node, shaderStage ) {
  56763. if ( shaderStage !== 'compute' ) {
  56764. if ( node.isAtomic === true ) {
  56765. warn( 'WebGPURenderer: Atomic operations are only supported in compute shaders.' );
  56766. return NodeAccess.READ_WRITE;
  56767. }
  56768. return NodeAccess.READ_ONLY;
  56769. }
  56770. return node.access;
  56771. }
  56772. /**
  56773. * Returns A WGSL snippet representing the storage access.
  56774. *
  56775. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  56776. * @param {string} shaderStage - The shader stage.
  56777. * @return {string} The WGSL snippet representing the storage access.
  56778. */
  56779. getStorageAccess( node, shaderStage ) {
  56780. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  56781. }
  56782. /**
  56783. * This method is one of the more important ones since it's responsible
  56784. * for generating a matching binding instance for the given uniform node.
  56785. *
  56786. * These bindings are later used in the renderer to create bind groups
  56787. * and layouts.
  56788. *
  56789. * @param {UniformNode} node - The uniform node.
  56790. * @param {string} type - The node data type.
  56791. * @param {string} shaderStage - The shader stage.
  56792. * @param {?string} [name=null] - An optional uniform name.
  56793. * @return {NodeUniform} The node uniform object.
  56794. */
  56795. getUniformFromNode( node, type, shaderStage, name = null ) {
  56796. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  56797. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  56798. if ( nodeData.uniformGPU === undefined ) {
  56799. let uniformGPU;
  56800. const group = node.groupNode;
  56801. const groupName = group.name;
  56802. const bindings = this.getBindGroupArray( groupName, shaderStage );
  56803. if ( type === 'texture' || type === 'cubeTexture' || type === 'cubeDepthTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  56804. let texture = null;
  56805. const access = this.getNodeAccess( node, shaderStage );
  56806. if ( type === 'texture' || type === 'storageTexture' ) {
  56807. if ( node.value.is3DTexture === true ) {
  56808. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  56809. } else {
  56810. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  56811. }
  56812. } else if ( type === 'cubeTexture' || type === 'cubeDepthTexture' ) {
  56813. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  56814. } else if ( type === 'texture3D' ) {
  56815. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  56816. }
  56817. texture.store = node.isStorageTextureNode === true;
  56818. texture.mipLevel = texture.store ? node.mipLevel : 0;
  56819. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  56820. // Cube textures always need samplers (they use textureSampleLevel, not textureLoad)
  56821. // Also textureGather always need sampler.
  56822. const needsSampler = node.value.isCubeTexture === true || ( this.isUnfilterable( node.value ) === false && texture.store === false ) || node.gatherNode !== null;
  56823. if ( needsSampler ) {
  56824. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  56825. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  56826. bindings.push( sampler, texture );
  56827. uniformGPU = [ sampler, texture ];
  56828. } else {
  56829. bindings.push( texture );
  56830. uniformGPU = [ texture ];
  56831. }
  56832. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  56833. const sharedData = this.getSharedDataFromNode( node );
  56834. let buffer = sharedData.buffer;
  56835. if ( buffer === undefined ) {
  56836. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  56837. buffer = new bufferClass( node, group );
  56838. sharedData.buffer = buffer;
  56839. }
  56840. buffer.setVisibility( buffer.getVisibility() | gpuShaderStageLib[ shaderStage ] );
  56841. bindings.push( buffer );
  56842. uniformGPU = buffer;
  56843. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  56844. } else {
  56845. let uniformsGroup = this.uniformGroups[ groupName ];
  56846. if ( uniformsGroup === undefined ) {
  56847. uniformsGroup = new NodeUniformsGroup( groupName, group );
  56848. uniformsGroup.setVisibility( GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT | GPUShaderStage.COMPUTE );
  56849. this.uniformGroups[ groupName ] = uniformsGroup;
  56850. }
  56851. // Add to bindings for this stage if not already present
  56852. if ( bindings.indexOf( uniformsGroup ) === -1 ) {
  56853. bindings.push( uniformsGroup );
  56854. }
  56855. uniformGPU = this.getNodeUniform( uniformNode, type );
  56856. // Only add uniform if not already present in the group (check by name to avoid duplicates across stages)
  56857. const uniformName = uniformGPU.name;
  56858. const alreadyExists = uniformsGroup.uniforms.some( u => u.name === uniformName );
  56859. if ( ! alreadyExists ) {
  56860. uniformsGroup.addUniform( uniformGPU );
  56861. }
  56862. }
  56863. nodeData.uniformGPU = uniformGPU;
  56864. }
  56865. return uniformNode;
  56866. }
  56867. /**
  56868. * This method should be used whenever builtins are required in nodes.
  56869. * The internal builtins data structure will make sure builtins are
  56870. * defined in the WGSL source.
  56871. *
  56872. * @param {string} name - The builtin name.
  56873. * @param {string} property - The property name.
  56874. * @param {string} type - The node data type.
  56875. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  56876. * @return {string} The property name.
  56877. */
  56878. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  56879. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  56880. if ( map.has( name ) === false ) {
  56881. map.set( name, {
  56882. name,
  56883. property,
  56884. type
  56885. } );
  56886. }
  56887. return property;
  56888. }
  56889. /**
  56890. * Returns `true` if the given builtin is defined in the given shader stage.
  56891. *
  56892. * @param {string} name - The builtin name.
  56893. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  56894. * @return {boolean} Whether the given builtin is defined in the given shader stage or not.
  56895. */
  56896. hasBuiltin( name, shaderStage = this.shaderStage ) {
  56897. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  56898. }
  56899. /**
  56900. * Returns the vertex index builtin.
  56901. *
  56902. * @return {string} The vertex index.
  56903. */
  56904. getVertexIndex() {
  56905. if ( this.shaderStage === 'vertex' ) {
  56906. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  56907. }
  56908. return 'vertexIndex';
  56909. }
  56910. /**
  56911. * Builds the given shader node.
  56912. *
  56913. * @param {ShaderNodeInternal} shaderNode - The shader node.
  56914. * @return {string} The WGSL function code.
  56915. */
  56916. buildFunctionCode( shaderNode ) {
  56917. const layout = shaderNode.layout;
  56918. const flowData = this.flowShaderNode( shaderNode );
  56919. const parameters = [];
  56920. for ( const input of layout.inputs ) {
  56921. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  56922. }
  56923. //
  56924. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  56925. ${ flowData.vars }
  56926. ${ flowData.code }
  56927. `;
  56928. if ( flowData.result ) {
  56929. code += `\treturn ${ flowData.result };\n`;
  56930. }
  56931. code += '\n}\n';
  56932. //
  56933. return code;
  56934. }
  56935. /**
  56936. * Contextually returns either the vertex stage instance index builtin
  56937. * or the linearized index of an compute invocation within a grid of workgroups.
  56938. *
  56939. * @return {string} The instance index.
  56940. */
  56941. getInstanceIndex() {
  56942. if ( this.shaderStage === 'vertex' ) {
  56943. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  56944. }
  56945. return 'instanceIndex';
  56946. }
  56947. /**
  56948. * Returns a builtin representing the index of a compute invocation within the scope of a workgroup load.
  56949. *
  56950. * @return {string} The invocation local index.
  56951. */
  56952. getInvocationLocalIndex() {
  56953. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  56954. }
  56955. /**
  56956. * Returns a builtin representing the size of a subgroup within the current shader.
  56957. *
  56958. * @return {string} The subgroup size.
  56959. */
  56960. getSubgroupSize() {
  56961. this.enableSubGroups();
  56962. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  56963. }
  56964. /**
  56965. * Returns a builtin representing the index of a compute invocation within the scope of a subgroup.
  56966. *
  56967. * @return {string} The invocation subgroup index.
  56968. */
  56969. getInvocationSubgroupIndex() {
  56970. this.enableSubGroups();
  56971. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  56972. }
  56973. /**
  56974. * Returns a builtin representing the index of a compute invocation's subgroup within its workgroup.
  56975. *
  56976. * @return {string} The subgroup index.
  56977. */
  56978. getSubgroupIndex() {
  56979. this.enableSubGroups();
  56980. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  56981. }
  56982. /**
  56983. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  56984. *
  56985. * @return {null} Null.
  56986. */
  56987. getDrawIndex() {
  56988. return null;
  56989. }
  56990. /**
  56991. * Returns the front facing builtin.
  56992. *
  56993. * @return {string} The front facing builtin.
  56994. */
  56995. getFrontFacing() {
  56996. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  56997. }
  56998. /**
  56999. * Returns the frag coord builtin.
  57000. *
  57001. * @return {string} The frag coord builtin.
  57002. */
  57003. getFragCoord() {
  57004. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  57005. }
  57006. /**
  57007. * Returns the frag depth builtin.
  57008. *
  57009. * @return {string} The frag depth builtin.
  57010. */
  57011. getFragDepth() {
  57012. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  57013. }
  57014. /**
  57015. * Returns the clip distances builtin.
  57016. *
  57017. * @return {string} The clip distances builtin.
  57018. */
  57019. getClipDistance() {
  57020. return 'varyings.hw_clip_distances';
  57021. }
  57022. /**
  57023. * Whether to flip texture data along its vertical axis or not.
  57024. *
  57025. * @return {boolean} Returns always `false` in context of WGSL.
  57026. */
  57027. isFlipY() {
  57028. return false;
  57029. }
  57030. /**
  57031. * Enables the given directive for the given shader stage.
  57032. *
  57033. * @param {string} name - The directive name.
  57034. * @param {string} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  57035. */
  57036. enableDirective( name, shaderStage = this.shaderStage ) {
  57037. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  57038. stage.add( name );
  57039. }
  57040. /**
  57041. * Returns the directives of the given shader stage as a WGSL string.
  57042. *
  57043. * @param {string} shaderStage - The shader stage.
  57044. * @return {string} A WGSL snippet that enables the directives of the given stage.
  57045. */
  57046. getDirectives( shaderStage ) {
  57047. const snippets = [];
  57048. const directives = this.directives[ shaderStage ];
  57049. if ( directives !== undefined ) {
  57050. for ( const directive of directives ) {
  57051. snippets.push( `enable ${directive};` );
  57052. }
  57053. }
  57054. return snippets.join( '\n' );
  57055. }
  57056. /**
  57057. * Enables the 'subgroups' directive.
  57058. */
  57059. enableSubGroups() {
  57060. this.enableDirective( 'subgroups' );
  57061. }
  57062. /**
  57063. * Enables the 'subgroups-f16' directive.
  57064. */
  57065. enableSubgroupsF16() {
  57066. this.enableDirective( 'subgroups-f16' );
  57067. }
  57068. /**
  57069. * Enables the 'clip_distances' directive.
  57070. */
  57071. enableClipDistances() {
  57072. this.enableDirective( 'clip_distances' );
  57073. }
  57074. /**
  57075. * Enables the 'f16' directive.
  57076. */
  57077. enableShaderF16() {
  57078. this.enableDirective( 'f16' );
  57079. }
  57080. /**
  57081. * Enables the 'dual_source_blending' directive.
  57082. */
  57083. enableDualSourceBlending() {
  57084. this.enableDirective( 'dual_source_blending' );
  57085. }
  57086. /**
  57087. * Enables hardware clipping.
  57088. *
  57089. * @param {string} planeCount - The clipping plane count.
  57090. */
  57091. enableHardwareClipping( planeCount ) {
  57092. this.enableClipDistances();
  57093. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  57094. }
  57095. /**
  57096. * Returns the builtins of the given shader stage as a WGSL string.
  57097. *
  57098. * @param {string} shaderStage - The shader stage.
  57099. * @return {string} A WGSL snippet that represents the builtins of the given stage.
  57100. */
  57101. getBuiltins( shaderStage ) {
  57102. const snippets = [];
  57103. const builtins = this.builtins[ shaderStage ];
  57104. if ( builtins !== undefined ) {
  57105. for ( const { name, property, type } of builtins.values() ) {
  57106. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  57107. }
  57108. }
  57109. return snippets.join( ',\n\t' );
  57110. }
  57111. /**
  57112. * This method should be used when a new scoped buffer is used in context of
  57113. * compute shaders. It adds the array to the internal data structure which is
  57114. * later used to generate the respective WGSL.
  57115. *
  57116. * @param {string} name - The array name.
  57117. * @param {string} scope - The scope.
  57118. * @param {string} bufferType - The buffer type.
  57119. * @param {string} bufferCount - The buffer count.
  57120. * @return {string} The array name.
  57121. */
  57122. getScopedArray( name, scope, bufferType, bufferCount ) {
  57123. if ( this.scopedArrays.has( name ) === false ) {
  57124. this.scopedArrays.set( name, {
  57125. name,
  57126. scope,
  57127. bufferType,
  57128. bufferCount
  57129. } );
  57130. }
  57131. return name;
  57132. }
  57133. /**
  57134. * Returns the scoped arrays of the given shader stage as a WGSL string.
  57135. *
  57136. * @param {string} shaderStage - The shader stage.
  57137. * @return {string|undefined} The WGSL snippet that defines the scoped arrays.
  57138. * Returns `undefined` when used in the vertex or fragment stage.
  57139. */
  57140. getScopedArrays( shaderStage ) {
  57141. if ( shaderStage !== 'compute' ) {
  57142. return;
  57143. }
  57144. const snippets = [];
  57145. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  57146. const type = this.getType( bufferType );
  57147. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  57148. }
  57149. return snippets.join( '\n' );
  57150. }
  57151. /**
  57152. * Returns the shader attributes of the given shader stage as a WGSL string.
  57153. *
  57154. * @param {string} shaderStage - The shader stage.
  57155. * @return {string} The WGSL snippet that defines the shader attributes.
  57156. */
  57157. getAttributes( shaderStage ) {
  57158. const snippets = [];
  57159. if ( shaderStage === 'compute' ) {
  57160. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  57161. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  57162. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  57163. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  57164. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  57165. this.enableDirective( 'subgroups', shaderStage );
  57166. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  57167. }
  57168. }
  57169. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  57170. const builtins = this.getBuiltins( 'attribute' );
  57171. if ( builtins ) snippets.push( builtins );
  57172. const attributes = this.getAttributesArray();
  57173. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  57174. const attribute = attributes[ index ];
  57175. const name = attribute.name;
  57176. const type = this.getType( attribute.type );
  57177. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  57178. }
  57179. }
  57180. return snippets.join( ',\n\t' );
  57181. }
  57182. /**
  57183. * Returns the members of the given struct type node as a WGSL string.
  57184. *
  57185. * @param {StructTypeNode} struct - The struct type node.
  57186. * @return {string} The WGSL snippet that defines the struct members.
  57187. */
  57188. getStructMembers( struct ) {
  57189. const snippets = [];
  57190. for ( const member of struct.members ) {
  57191. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  57192. let type = this.getType( member.type );
  57193. if ( member.atomic ) {
  57194. type = 'atomic< ' + type + ' >';
  57195. }
  57196. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  57197. }
  57198. if ( struct.output ) {
  57199. snippets.push( `\t${ this.getBuiltins( 'output' ) }` );
  57200. }
  57201. return snippets.join( ',\n' );
  57202. }
  57203. /**
  57204. * Returns the structs of the given shader stage as a WGSL string.
  57205. *
  57206. * @param {string} shaderStage - The shader stage.
  57207. * @return {string} The WGSL snippet that defines the structs.
  57208. */
  57209. getStructs( shaderStage ) {
  57210. let result = '';
  57211. const structs = this.structs[ shaderStage ];
  57212. if ( structs.length > 0 ) {
  57213. const snippets = [];
  57214. for ( const struct of structs ) {
  57215. let snippet = `struct ${ struct.name } {\n`;
  57216. snippet += this.getStructMembers( struct );
  57217. snippet += '\n};';
  57218. snippets.push( snippet );
  57219. }
  57220. result = '\n' + snippets.join( '\n\n' ) + '\n';
  57221. }
  57222. return result;
  57223. }
  57224. /**
  57225. * Returns a WGSL string representing a variable.
  57226. *
  57227. * @param {string} type - The variable's type.
  57228. * @param {string} name - The variable's name.
  57229. * @param {?number} [count=null] - The array length.
  57230. * @param {string} [qualifier=''] - The variable's qualifier.
  57231. * @return {string} The WGSL snippet that defines a variable.
  57232. */
  57233. getVar( type, name, count = null, qualifier = '' ) {
  57234. let snippet = `var${ qualifier } ${ name } : `;
  57235. if ( count !== null ) {
  57236. snippet += this.generateArrayDeclaration( type, count );
  57237. } else {
  57238. snippet += this.getType( type );
  57239. }
  57240. return snippet;
  57241. }
  57242. /**
  57243. * Returns the variables of the given shader stage as a WGSL string.
  57244. *
  57245. * @param {string} shaderStage - The shader stage.
  57246. * @return {string} The WGSL snippet that defines the variables.
  57247. */
  57248. getVars( shaderStage, global = false ) {
  57249. let qualifier = '';
  57250. if ( global ) {
  57251. qualifier = '<private>';
  57252. }
  57253. const snippets = [];
  57254. const vars = this.vars[ shaderStage ];
  57255. if ( vars !== undefined ) {
  57256. for ( const variable of vars ) {
  57257. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count, qualifier ) };` );
  57258. }
  57259. }
  57260. return global ? snippets.join( '\n' ) : `\n\t${ snippets.join( '\n\t' ) }\n`;
  57261. }
  57262. /**
  57263. * Returns the varyings of the given shader stage as a WGSL string.
  57264. *
  57265. * @param {string} shaderStage - The shader stage.
  57266. * @return {string} The WGSL snippet that defines the varyings.
  57267. */
  57268. getVaryings( shaderStage ) {
  57269. const snippets = [];
  57270. if ( shaderStage === 'vertex' ) {
  57271. this.getBuiltin( 'position', 'builtinClipSpace', 'vec4<f32>', 'vertex' );
  57272. }
  57273. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  57274. const varyings = this.varyings;
  57275. const vars = this.vars[ shaderStage ];
  57276. let varyingIndex = 0;
  57277. for ( let index = 0; index < varyings.length; index ++ ) {
  57278. const varying = varyings[ index ];
  57279. if ( varying.needsInterpolation ) {
  57280. let attributesSnippet = `@location( ${ varyingIndex ++ } )`;
  57281. if ( varying.interpolationType ) {
  57282. const samplingSnippet = varying.interpolationSampling !== null ? `, ${ varying.interpolationSampling } )` : ' )';
  57283. attributesSnippet += ` @interpolate( ${ varying.interpolationType }${ samplingSnippet }`;
  57284. // Otherwise, optimize interpolation when sensible
  57285. } else if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  57286. attributesSnippet += ' @interpolate(flat, either)';
  57287. }
  57288. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  57289. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  57290. vars.push( varying );
  57291. }
  57292. }
  57293. }
  57294. const builtins = this.getBuiltins( shaderStage );
  57295. if ( builtins ) snippets.push( builtins );
  57296. const code = snippets.join( ',\n\t' );
  57297. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  57298. }
  57299. isCustomStruct( nodeUniform ) {
  57300. const attribute = nodeUniform.value;
  57301. const bufferNode = nodeUniform.node;
  57302. const isAttributeStructType = ( attribute.isBufferAttribute || attribute.isInstancedBufferAttribute ) && bufferNode.structTypeNode !== null;
  57303. const isStructArray =
  57304. ( bufferNode.value && bufferNode.value.array ) &&
  57305. ( typeof bufferNode.value.itemSize === 'number' && bufferNode.value.array.length > bufferNode.value.itemSize );
  57306. return isAttributeStructType && ! isStructArray;
  57307. }
  57308. /**
  57309. * Returns the uniforms of the given shader stage as a WGSL string.
  57310. *
  57311. * @param {string} shaderStage - The shader stage.
  57312. * @return {string} The WGSL snippet that defines the uniforms.
  57313. */
  57314. getUniforms( shaderStage ) {
  57315. const backend = this.renderer.backend;
  57316. const uniforms = this.uniforms[ shaderStage ];
  57317. const bindingSnippets = [];
  57318. const bufferSnippets = [];
  57319. const structSnippets = [];
  57320. const uniformGroups = {};
  57321. for ( const uniform of uniforms ) {
  57322. const groupName = uniform.groupNode.name;
  57323. const uniformIndexes = this.bindingsIndexes[ groupName ];
  57324. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'cubeDepthTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  57325. const textureNode = uniform.node;
  57326. const texture = textureNode.value;
  57327. // Cube textures always need samplers (they use textureSampleLevel, not textureLoad)
  57328. // Also textureGather always need sampler.
  57329. const needsSampler = texture.isCubeTexture === true || ( this.isUnfilterable( texture ) === false && textureNode.isStorageTextureNode !== true ) || textureNode.gatherNode !== null;
  57330. if ( needsSampler ) {
  57331. if ( this.isSampleCompare( texture ) && textureNode.compareNode !== null ) {
  57332. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  57333. } else {
  57334. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  57335. }
  57336. }
  57337. let textureType;
  57338. let multisampled = '';
  57339. const { primarySamples } = backend.utils.getTextureSampleData( texture );
  57340. if ( primarySamples > 1 ) {
  57341. multisampled = '_multisampled';
  57342. }
  57343. if ( texture.isCubeTexture === true && texture.isDepthTexture === true ) {
  57344. textureType = 'texture_depth_cube';
  57345. } else if ( texture.isCubeTexture === true ) {
  57346. textureType = 'texture_cube<f32>';
  57347. } else if ( texture.isDepthTexture === true ) {
  57348. if ( backend.compatibilityMode && texture.compareFunction === null ) {
  57349. textureType = `texture${ multisampled }_2d<f32>`;
  57350. } else {
  57351. textureType = `texture_depth${ multisampled }_2d${ texture.isArrayTexture === true ? '_array' : '' }`;
  57352. }
  57353. } else if ( uniform.node.isStorageTextureNode === true ) {
  57354. const format = getFormat( texture, backend.device );
  57355. const access = this.getStorageAccess( uniform.node, shaderStage );
  57356. const is3D = uniform.node.value.is3DTexture;
  57357. const isArrayTexture = uniform.node.value.isArrayTexture;
  57358. const dimension = is3D ? '3d' : `2d${ isArrayTexture ? '_array' : '' }`;
  57359. textureType = `texture_storage_${ dimension }<${ format }, ${ access }>`;
  57360. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  57361. textureType = 'texture_2d_array<f32>';
  57362. } else if ( texture.is3DTexture === true || texture.isData3DTexture === true ) {
  57363. textureType = 'texture_3d<f32>';
  57364. } else {
  57365. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  57366. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  57367. }
  57368. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  57369. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  57370. const bufferNode = uniform.node;
  57371. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  57372. const bufferCount = bufferNode.bufferCount;
  57373. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  57374. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  57375. if ( this.isCustomStruct( uniform ) ) {
  57376. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  57377. } else {
  57378. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  57379. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  57380. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  57381. }
  57382. } else {
  57383. const groupName = uniform.groupNode.name;
  57384. // Check if this group has already been processed in this shader stage
  57385. if ( uniformGroups[ groupName ] === undefined ) {
  57386. // Get the shared uniform group that contains uniforms from all stages
  57387. const sharedUniformGroup = this.uniformGroups[ groupName ];
  57388. if ( sharedUniformGroup !== undefined ) {
  57389. // Generate snippets for ALL uniforms in this shared group
  57390. const snippets = [];
  57391. for ( const sharedUniform of sharedUniformGroup.uniforms ) {
  57392. const type = sharedUniform.getType();
  57393. const vectorType = this.getType( this.getVectorType( type ) );
  57394. snippets.push( `\t${ sharedUniform.name } : ${ vectorType }` );
  57395. }
  57396. // Check if this group already has an assigned binding index (from another shader stage)
  57397. let groupBinding = this.uniformGroupsBindings[ groupName ];
  57398. if ( groupBinding === undefined ) {
  57399. // First time processing this group - assign a new binding index
  57400. groupBinding = {
  57401. index: uniformIndexes.binding ++,
  57402. id: uniformIndexes.group
  57403. };
  57404. this.uniformGroupsBindings[ groupName ] = groupBinding;
  57405. }
  57406. uniformGroups[ groupName ] = {
  57407. index: groupBinding.index,
  57408. id: groupBinding.id,
  57409. snippets: snippets
  57410. };
  57411. }
  57412. }
  57413. }
  57414. }
  57415. for ( const name in uniformGroups ) {
  57416. const group = uniformGroups[ name ];
  57417. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  57418. }
  57419. const code = [ ...bindingSnippets, ...bufferSnippets, ...structSnippets ].join( '\n' );
  57420. return code;
  57421. }
  57422. /**
  57423. * Controls the code build of the shader stages.
  57424. */
  57425. buildCode() {
  57426. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  57427. this.sortBindingGroups();
  57428. for ( const shaderStage in shadersData ) {
  57429. this.shaderStage = shaderStage;
  57430. const allowGlobal = this.allowGlobalVariables;
  57431. const stageData = shadersData[ shaderStage ];
  57432. stageData.uniforms = this.getUniforms( shaderStage );
  57433. stageData.attributes = this.getAttributes( shaderStage );
  57434. stageData.varyings = this.getVaryings( shaderStage );
  57435. stageData.structs = this.getStructs( shaderStage );
  57436. stageData.vars = this.getVars( shaderStage, allowGlobal );
  57437. stageData.codes = this.getCodes( shaderStage );
  57438. stageData.directives = this.getDirectives( shaderStage );
  57439. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  57440. //
  57441. let flow = '// code\n\n';
  57442. flow += this.flowCode[ shaderStage ];
  57443. const flowNodes = this.flowNodes[ shaderStage ];
  57444. const mainNode = flowNodes[ flowNodes.length - 1 ];
  57445. const outputNode = mainNode.outputNode;
  57446. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  57447. for ( const node of flowNodes ) {
  57448. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  57449. const slotName = node.name;
  57450. if ( slotName ) {
  57451. if ( flow.length > 0 ) flow += '\n';
  57452. flow += `\t// flow -> ${ slotName }\n`;
  57453. }
  57454. flow += `${ flowSlotData.code }\n\t`;
  57455. if ( node === mainNode && shaderStage !== 'compute' ) {
  57456. flow += '// result\n\n\t';
  57457. if ( shaderStage === 'vertex' ) {
  57458. flow += `varyings.builtinClipSpace = ${ flowSlotData.result };`;
  57459. } else if ( shaderStage === 'fragment' ) {
  57460. if ( isOutputStruct ) {
  57461. stageData.returnType = outputNode.getNodeType( this );
  57462. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  57463. flow += `return ${ flowSlotData.result };`;
  57464. } else {
  57465. let structSnippet = `\t@location( 0 ) color: ${ this.getType( this.getOutputType() ) }`;
  57466. const builtins = this.getBuiltins( 'output' );
  57467. if ( builtins ) structSnippet += ',\n\t' + builtins;
  57468. stageData.returnType = 'OutputStruct';
  57469. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  57470. stageData.structs += '\nvar<private> output : OutputStruct;';
  57471. flow += `output.color = ${ this.format( flowSlotData.result, mainNode.getNodeType( this ), this.getOutputType() ) };\n\n\treturn output;`;
  57472. }
  57473. }
  57474. }
  57475. }
  57476. stageData.flow = flow;
  57477. }
  57478. this.shaderStage = null;
  57479. if ( this.material !== null ) {
  57480. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  57481. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  57482. } else {
  57483. // Early strictly validated in computeNode
  57484. const workgroupSize = this.object.workgroupSize;
  57485. this.computeShader = this._getWGSLComputeCode( shadersData.compute, workgroupSize );
  57486. }
  57487. }
  57488. /**
  57489. * Returns the native shader method name for a given generic name.
  57490. *
  57491. * @param {string} method - The method name to resolve.
  57492. * @param {?string} [output=null] - An optional output.
  57493. * @return {string} The resolved WGSL method name.
  57494. */
  57495. getMethod( method, output = null ) {
  57496. let wgslMethod;
  57497. if ( output !== null ) {
  57498. wgslMethod = this._getWGSLMethod( method + '_' + output );
  57499. }
  57500. if ( wgslMethod === undefined ) {
  57501. wgslMethod = this._getWGSLMethod( method );
  57502. }
  57503. return wgslMethod || method;
  57504. }
  57505. /**
  57506. * Returns the bitcast method name for a given input and outputType.
  57507. *
  57508. * @param {string} type - The output type to bitcast to.
  57509. * @return {string} The resolved WGSL bitcast invocation.
  57510. */
  57511. getBitcastMethod( type ) {
  57512. const dataType = this.getType( type );
  57513. return `bitcast<${ dataType }>`;
  57514. }
  57515. /**
  57516. * Returns the float packing method name for a given numeric encoding.
  57517. *
  57518. * @param {string} encoding - The numeric encoding that describes how the float values are mapped to the integer range.
  57519. * @returns {string} The resolve WGSL float packing method name.
  57520. */
  57521. getFloatPackingMethod( encoding ) {
  57522. return this.getMethod( `floatpack_${ encoding }_2x16` );
  57523. }
  57524. /**
  57525. * Returns the float unpacking method name for a given numeric encoding.
  57526. *
  57527. * @param {string} encoding - The numeric encoding that describes how the integer values are mapped to the float range.
  57528. * @returns {string} The resolve WGSL float unpacking method name.
  57529. */
  57530. getFloatUnpackingMethod( encoding ) {
  57531. return this.getMethod( `floatunpack_${ encoding }_2x16` );
  57532. }
  57533. /**
  57534. * Returns the native snippet for a ternary operation.
  57535. *
  57536. * @param {string} condSnippet - The condition determining which expression gets resolved.
  57537. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  57538. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  57539. * @return {string} The resolved method name.
  57540. */
  57541. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  57542. return `select( ${elseSnippet}, ${ifSnippet}, ${condSnippet} )`;
  57543. }
  57544. /**
  57545. * Returns the WGSL type of the given node data type.
  57546. *
  57547. * @param {string} type - The node data type.
  57548. * @return {string} The WGSL type.
  57549. */
  57550. getType( type ) {
  57551. return wgslTypeLib[ type ] || type;
  57552. }
  57553. /**
  57554. * Whether the requested feature is available or not.
  57555. *
  57556. * @param {string} name - The requested feature.
  57557. * @return {boolean} Whether the requested feature is supported or not.
  57558. */
  57559. isAvailable( name ) {
  57560. let result = supports[ name ];
  57561. if ( result === undefined ) {
  57562. if ( name === 'float32Filterable' ) {
  57563. result = this.renderer.hasFeature( 'float32-filterable' );
  57564. } else if ( name === 'clipDistance' ) {
  57565. result = this.renderer.hasFeature( 'clip-distances' );
  57566. }
  57567. supports[ name ] = result;
  57568. }
  57569. return result;
  57570. }
  57571. /**
  57572. * Returns the native shader method name for a given generic name.
  57573. *
  57574. * @private
  57575. * @param {string} method - The method name to resolve.
  57576. * @return {string} The resolved WGSL method name.
  57577. */
  57578. _getWGSLMethod( method ) {
  57579. if ( wgslPolyfill[ method ] !== undefined ) {
  57580. this._include( method );
  57581. }
  57582. return wgslMethods[ method ];
  57583. }
  57584. /**
  57585. * Includes the given method name into the current
  57586. * function node.
  57587. *
  57588. * @private
  57589. * @param {string} name - The method name to include.
  57590. * @return {CodeNode} The respective code node.
  57591. */
  57592. _include( name ) {
  57593. const codeNode = wgslPolyfill[ name ];
  57594. codeNode.build( this );
  57595. this.addInclude( codeNode );
  57596. return codeNode;
  57597. }
  57598. /**
  57599. * Returns a WGSL vertex shader based on the given shader data.
  57600. *
  57601. * @private
  57602. * @param {Object} shaderData - The shader data.
  57603. * @return {string} The vertex shader.
  57604. */
  57605. _getWGSLVertexCode( shaderData ) {
  57606. return `${ this.getSignature() }
  57607. // directives
  57608. ${shaderData.directives}
  57609. // structs
  57610. ${shaderData.structs}
  57611. // uniforms
  57612. ${shaderData.uniforms}
  57613. // varyings
  57614. ${shaderData.varyings}
  57615. var<private> varyings : VaryingsStruct;
  57616. // vars
  57617. ${shaderData.vars}
  57618. // codes
  57619. ${shaderData.codes}
  57620. @vertex
  57621. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  57622. // flow
  57623. ${shaderData.flow}
  57624. return varyings;
  57625. }
  57626. `;
  57627. }
  57628. /**
  57629. * Returns a WGSL fragment shader based on the given shader data.
  57630. *
  57631. * @private
  57632. * @param {Object} shaderData - The shader data.
  57633. * @return {string} The vertex shader.
  57634. */
  57635. _getWGSLFragmentCode( shaderData ) {
  57636. return `${ this.getSignature() }
  57637. // global
  57638. ${ diagnostics }
  57639. // structs
  57640. ${shaderData.structs}
  57641. // uniforms
  57642. ${shaderData.uniforms}
  57643. // vars
  57644. ${shaderData.vars}
  57645. // codes
  57646. ${shaderData.codes}
  57647. @fragment
  57648. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  57649. // flow
  57650. ${shaderData.flow}
  57651. }
  57652. `;
  57653. }
  57654. /**
  57655. * Returns a WGSL compute shader based on the given shader data.
  57656. *
  57657. * @private
  57658. * @param {Object} shaderData - The shader data.
  57659. * @param {string} workgroupSize - The workgroup size.
  57660. * @return {string} The vertex shader.
  57661. */
  57662. _getWGSLComputeCode( shaderData, workgroupSize ) {
  57663. const [ workgroupSizeX, workgroupSizeY, workgroupSizeZ ] = workgroupSize;
  57664. return `${ this.getSignature() }
  57665. // directives
  57666. ${ shaderData.directives }
  57667. // system
  57668. var<private> instanceIndex : u32;
  57669. // locals
  57670. ${ shaderData.scopedArrays }
  57671. // structs
  57672. ${ shaderData.structs }
  57673. // uniforms
  57674. ${ shaderData.uniforms }
  57675. // vars
  57676. ${ this.allowGlobalVariables ? shaderData.vars : '' }
  57677. // codes
  57678. ${ shaderData.codes }
  57679. @compute @workgroup_size( ${ workgroupSizeX }, ${ workgroupSizeY }, ${ workgroupSizeZ } )
  57680. fn main( ${ shaderData.attributes } ) {
  57681. // local vars
  57682. ${ this.allowGlobalVariables ? '' : shaderData.vars }
  57683. // system
  57684. instanceIndex = globalId.x
  57685. + globalId.y * ( ${ workgroupSizeX } * numWorkgroups.x )
  57686. + globalId.z * ( ${ workgroupSizeX } * numWorkgroups.x ) * ( ${ workgroupSizeY } * numWorkgroups.y );
  57687. // flow
  57688. ${ shaderData.flow }
  57689. }
  57690. `;
  57691. }
  57692. /**
  57693. * Returns a WGSL struct based on the given name and variables.
  57694. *
  57695. * @private
  57696. * @param {string} name - The struct name.
  57697. * @param {string} vars - The struct variables.
  57698. * @return {string} The WGSL snippet representing a struct.
  57699. */
  57700. _getWGSLStruct( name, vars ) {
  57701. return `
  57702. struct ${name} {
  57703. ${vars}
  57704. };`;
  57705. }
  57706. /**
  57707. * Returns a WGSL struct binding.
  57708. *
  57709. * @private
  57710. * @param {string} name - The struct name.
  57711. * @param {string} vars - The struct variables.
  57712. * @param {string} access - The access.
  57713. * @param {number} [binding=0] - The binding index.
  57714. * @param {number} [group=0] - The group index.
  57715. * @return {string} The WGSL snippet representing a struct binding.
  57716. */
  57717. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  57718. const structName = name + 'Struct';
  57719. const structSnippet = this._getWGSLStruct( structName, vars );
  57720. return `${structSnippet}
  57721. @binding( ${ binding } ) @group( ${ group } )
  57722. var<${access}> ${ name } : ${ structName };`;
  57723. }
  57724. }
  57725. const _bufferDescriptor$3 = new GPUBufferDescriptor();
  57726. const _commandEncoderDescriptor$2 = new GPUCommandEncoderDescriptor();
  57727. const typedArraysToVertexFormatPrefix = new Map( [
  57728. [ Int8Array, [ 'sint8', 'snorm8' ]],
  57729. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  57730. [ Int16Array, [ 'sint16', 'snorm16' ]],
  57731. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  57732. [ Int32Array, [ 'sint32', 'snorm32' ]],
  57733. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  57734. [ Float32Array, [ 'float32', ]],
  57735. ] );
  57736. if ( typeof Float16Array !== 'undefined' ) {
  57737. typedArraysToVertexFormatPrefix.set( Float16Array, [ 'float16' ] );
  57738. }
  57739. const typedAttributeToVertexFormatPrefix = new Map( [
  57740. [ Float16BufferAttribute, [ 'float16', ]],
  57741. ] );
  57742. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  57743. [ Int32Array, 'sint32' ],
  57744. [ Int16Array, 'sint32' ], // patch for INT16
  57745. [ Uint32Array, 'uint32' ],
  57746. [ Uint16Array, 'uint32' ], // patch for UINT16
  57747. [ Float32Array, 'float32' ]
  57748. ] );
  57749. /**
  57750. * A WebGPU backend utility module for managing shader attributes.
  57751. *
  57752. * @private
  57753. */
  57754. class WebGPUAttributeUtils {
  57755. /**
  57756. * Constructs a new utility object.
  57757. *
  57758. * @param {WebGPUBackend} backend - The WebGPU backend.
  57759. */
  57760. constructor( backend ) {
  57761. /**
  57762. * A reference to the WebGPU backend.
  57763. *
  57764. * @type {WebGPUBackend}
  57765. */
  57766. this.backend = backend;
  57767. }
  57768. /**
  57769. * Creates the GPU buffer for the given buffer attribute.
  57770. *
  57771. * @param {BufferAttribute} attribute - The buffer attribute.
  57772. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  57773. */
  57774. createAttribute( attribute, usage ) {
  57775. const bufferAttribute = this._getBufferAttribute( attribute );
  57776. const backend = this.backend;
  57777. const bufferData = backend.get( bufferAttribute );
  57778. let buffer = bufferData.buffer;
  57779. if ( buffer === undefined ) {
  57780. const device = backend.device;
  57781. let array = bufferAttribute.array;
  57782. // patch for INT16 and UINT16
  57783. if ( attribute.normalized === false ) {
  57784. if ( array.constructor === Int16Array || array.constructor === Int8Array ) {
  57785. array = new Int32Array( array );
  57786. } else if ( array.constructor === Uint16Array || array.constructor === Uint8Array ) {
  57787. array = new Uint32Array( array );
  57788. if ( usage & GPUBufferUsage.INDEX ) {
  57789. for ( let i = 0; i < array.length; i ++ ) {
  57790. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  57791. }
  57792. }
  57793. }
  57794. }
  57795. bufferAttribute.array = array;
  57796. let paddedItemSize;
  57797. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  57798. // WGSL does not support packed vec3 data in storage buffers, pad to vec4
  57799. paddedItemSize = 4;
  57800. } else if ( bufferAttribute.itemSize > 1 && ( bufferAttribute.itemSize * array.BYTES_PER_ELEMENT ) % 4 !== 0 ) {
  57801. // arrayStride must be a multiple of 4
  57802. const byteStride = bufferAttribute.itemSize * array.BYTES_PER_ELEMENT;
  57803. paddedItemSize = ( Math.floor( ( byteStride + 3 ) / 4 ) * 4 ) / array.BYTES_PER_ELEMENT;
  57804. }
  57805. if ( paddedItemSize !== undefined ) {
  57806. const itemSize = bufferAttribute.itemSize;
  57807. const paddedArray = new array.constructor( bufferAttribute.count * paddedItemSize );
  57808. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  57809. paddedArray.set( array.subarray( i * itemSize, i * itemSize + itemSize ), i * paddedItemSize );
  57810. }
  57811. if ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) {
  57812. // update the storage attribute so storage bindings access the padded layout
  57813. bufferAttribute.itemSize = paddedItemSize;
  57814. bufferAttribute.array = paddedArray;
  57815. }
  57816. array = paddedArray;
  57817. // save the original and padded item size so buffer updates can apply the same padding
  57818. bufferData._itemSize = itemSize;
  57819. bufferData._paddedItemSize = paddedItemSize;
  57820. }
  57821. // total buffer size must be a multiple of 4
  57822. const byteLength = array.byteLength;
  57823. const size = byteLength + ( ( 4 - ( byteLength % 4 ) ) % 4 );
  57824. _bufferDescriptor$3.label = bufferAttribute.name;
  57825. _bufferDescriptor$3.size = size;
  57826. _bufferDescriptor$3.usage = usage;
  57827. _bufferDescriptor$3.mappedAtCreation = true;
  57828. buffer = device.createBuffer( _bufferDescriptor$3 );
  57829. _bufferDescriptor$3.reset();
  57830. new array.constructor( buffer.getMappedRange() ).set( array );
  57831. buffer.unmap();
  57832. bufferData.buffer = buffer;
  57833. }
  57834. }
  57835. /**
  57836. * Updates the GPU buffer of the given buffer attribute.
  57837. *
  57838. * @param {BufferAttribute} attribute - The buffer attribute.
  57839. */
  57840. updateAttribute( attribute ) {
  57841. const bufferAttribute = this._getBufferAttribute( attribute );
  57842. const backend = this.backend;
  57843. const device = backend.device;
  57844. const bufferData = backend.get( bufferAttribute );
  57845. const buffer = backend.get( bufferAttribute ).buffer;
  57846. let array = bufferAttribute.array;
  57847. const itemSize = bufferData._itemSize;
  57848. const paddedItemSize = bufferData._paddedItemSize;
  57849. if ( paddedItemSize !== undefined ) {
  57850. // if the attribute data were padded on upload, apply the same padding on updates.
  57851. array = new array.constructor( bufferAttribute.count * paddedItemSize );
  57852. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  57853. array.set( bufferAttribute.array.subarray( i * itemSize, i * itemSize + itemSize ), i * paddedItemSize );
  57854. }
  57855. if ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) {
  57856. // keep the storage attribute in sync with the padded layout
  57857. bufferAttribute.array = array;
  57858. }
  57859. }
  57860. const updateRanges = bufferAttribute.updateRanges;
  57861. if ( updateRanges.length === 0 ) {
  57862. // Not using update ranges
  57863. device.queue.writeBuffer(
  57864. buffer,
  57865. 0,
  57866. array,
  57867. 0
  57868. );
  57869. } else {
  57870. const isTyped = isTypedArray( array );
  57871. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  57872. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  57873. const range = updateRanges[ i ];
  57874. let dataOffset, size;
  57875. if ( paddedItemSize !== undefined ) {
  57876. const vertexStart = Math.floor( range.start / itemSize );
  57877. const vertexCount = Math.ceil( ( range.start + range.count ) / itemSize ) - vertexStart;
  57878. dataOffset = vertexStart * paddedItemSize * byteOffsetFactor;
  57879. size = vertexCount * paddedItemSize * byteOffsetFactor;
  57880. } else {
  57881. dataOffset = range.start * byteOffsetFactor;
  57882. size = range.count * byteOffsetFactor;
  57883. }
  57884. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  57885. device.queue.writeBuffer(
  57886. buffer,
  57887. bufferOffset,
  57888. array,
  57889. dataOffset,
  57890. size
  57891. );
  57892. }
  57893. bufferAttribute.clearUpdateRanges();
  57894. }
  57895. }
  57896. /**
  57897. * This method creates the vertex buffer layout data which are
  57898. * require when creating a render pipeline for the given render object.
  57899. *
  57900. * @param {RenderObject} renderObject - The render object.
  57901. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  57902. */
  57903. createShaderVertexBuffers( renderObject ) {
  57904. const attributes = renderObject.getAttributes();
  57905. const vertexBuffers = new Map();
  57906. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  57907. const geometryAttribute = attributes[ slot ];
  57908. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  57909. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  57910. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  57911. if ( vertexBufferLayout === undefined ) {
  57912. let arrayStride, stepMode;
  57913. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  57914. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  57915. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  57916. } else {
  57917. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  57918. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  57919. if ( geometryAttribute.itemSize > 1 && arrayStride % 4 !== 0 ) {
  57920. // packed attribute data are padded per vertex on upload
  57921. arrayStride = Math.floor( ( arrayStride + 3 ) / 4 ) * 4;
  57922. }
  57923. }
  57924. // patch for INT16 and UINT16
  57925. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  57926. arrayStride = 4;
  57927. }
  57928. vertexBufferLayout = {
  57929. arrayStride,
  57930. attributes: [],
  57931. stepMode
  57932. };
  57933. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  57934. }
  57935. const format = this._getVertexFormat( geometryAttribute );
  57936. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  57937. vertexBufferLayout.attributes.push( {
  57938. shaderLocation: slot,
  57939. offset,
  57940. format
  57941. } );
  57942. }
  57943. return Array.from( vertexBuffers.values() );
  57944. }
  57945. /**
  57946. * Destroys the GPU buffer of the given buffer attribute.
  57947. *
  57948. * @param {BufferAttribute} attribute - The buffer attribute.
  57949. */
  57950. destroyAttribute( attribute ) {
  57951. const backend = this.backend;
  57952. const data = backend.get( this._getBufferAttribute( attribute ) );
  57953. data.buffer.destroy();
  57954. backend.delete( attribute );
  57955. }
  57956. /**
  57957. * This method performs a readback operation by moving buffer data from
  57958. * a storage buffer attribute from the GPU to the CPU. ReadbackBuffer can
  57959. * be used to retain and reuse handles to the intermediate buffers and prevent
  57960. * new allocation.
  57961. *
  57962. * @async
  57963. * @param {BufferAttribute} attribute - The storage buffer attribute to read frm.
  57964. * @param {number} count - The offset from which to start reading the
  57965. * @param {number} offset - The storage buffer attribute.
  57966. * @param {ReadbackBuffer|ArrayBuffer} target - The storage buffer attribute.
  57967. * @return {Promise<ArrayBuffer|ReadbackBuffer>} A promise that resolves with the buffer data when the data are ready.
  57968. */
  57969. async getArrayBufferAsync( attribute, target = null, offset = 0, count = -1 ) {
  57970. const backend = this.backend;
  57971. const device = backend.device;
  57972. const data = backend.get( this._getBufferAttribute( attribute ) );
  57973. const bufferGPU = data.buffer;
  57974. const byteLength = count === -1 ? bufferGPU.size - offset : count;
  57975. let readBufferGPU;
  57976. if ( target !== null && target.isReadbackBuffer ) {
  57977. const readbackInfo = backend.get( target );
  57978. if ( target._mapped === true ) {
  57979. throw new Error( 'THREE.WebGPUAttributeUtils: ReadbackBuffer must be released before being used again.' );
  57980. }
  57981. target._mapped = true;
  57982. // initialize the GPU-side read copy buffer if it is not present
  57983. if ( readbackInfo.readBufferGPU === undefined ) {
  57984. _bufferDescriptor$3.label = `${ target.name }_readback`;
  57985. _bufferDescriptor$3.size = target.maxByteLength;
  57986. _bufferDescriptor$3.usage = GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ;
  57987. readBufferGPU = device.createBuffer( _bufferDescriptor$3 );
  57988. _bufferDescriptor$3.reset();
  57989. // release / dispose
  57990. const releaseCallback = () => {
  57991. target.buffer = null;
  57992. target._mapped = false;
  57993. readBufferGPU.unmap();
  57994. };
  57995. const disposeCallback = () => {
  57996. target.buffer = null;
  57997. target._mapped = false;
  57998. readBufferGPU.destroy();
  57999. backend.delete( target );
  58000. target.removeEventListener( 'release', releaseCallback );
  58001. target.removeEventListener( 'dispose', disposeCallback );
  58002. };
  58003. target.addEventListener( 'release', releaseCallback );
  58004. target.addEventListener( 'dispose', disposeCallback );
  58005. // register
  58006. readbackInfo.readBufferGPU = readBufferGPU;
  58007. } else {
  58008. readBufferGPU = readbackInfo.readBufferGPU;
  58009. }
  58010. } else {
  58011. // create a new temp buffer for array buffers otherwise
  58012. _bufferDescriptor$3.label = `${ attribute.name }_readback`;
  58013. _bufferDescriptor$3.size = byteLength;
  58014. _bufferDescriptor$3.usage = GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ;
  58015. readBufferGPU = device.createBuffer( _bufferDescriptor$3 );
  58016. _bufferDescriptor$3.reset();
  58017. }
  58018. // copy the data
  58019. _commandEncoderDescriptor$2.label = `readback_encoder_${ attribute.name }`;
  58020. const cmdEncoder = device.createCommandEncoder( _commandEncoderDescriptor$2 );
  58021. _commandEncoderDescriptor$2.reset();
  58022. cmdEncoder.copyBufferToBuffer(
  58023. bufferGPU,
  58024. offset,
  58025. readBufferGPU,
  58026. 0,
  58027. byteLength,
  58028. );
  58029. const gpuCommands = cmdEncoder.finish();
  58030. submit( device, gpuCommands );
  58031. // map the data to the CPU
  58032. await readBufferGPU.mapAsync( GPUMapMode.READ, 0, byteLength );
  58033. if ( target === null ) {
  58034. // return a new array buffer and clean up the gpu handles
  58035. const arrayBuffer = readBufferGPU.getMappedRange( 0, byteLength );
  58036. const result = arrayBuffer.slice();
  58037. readBufferGPU.destroy();
  58038. return result;
  58039. } else if ( target.isReadbackBuffer ) {
  58040. // assign the data to the read back handle
  58041. target.buffer = readBufferGPU.getMappedRange( 0, byteLength );
  58042. return target;
  58043. } else {
  58044. // copy the data into the target array buffer
  58045. const arrayBuffer = readBufferGPU.getMappedRange( 0, byteLength );
  58046. new Uint8Array( target ).set( new Uint8Array( arrayBuffer ) );
  58047. readBufferGPU.destroy();
  58048. return target;
  58049. }
  58050. }
  58051. /**
  58052. * Returns the vertex format of the given buffer attribute.
  58053. *
  58054. * @private
  58055. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  58056. * @return {string|undefined} The vertex format (e.g. 'float32x3').
  58057. */
  58058. _getVertexFormat( geometryAttribute ) {
  58059. const { itemSize, normalized } = geometryAttribute;
  58060. const ArrayType = geometryAttribute.array.constructor;
  58061. const AttributeType = geometryAttribute.constructor;
  58062. let format;
  58063. if ( itemSize === 1 ) {
  58064. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  58065. } else {
  58066. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  58067. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  58068. if ( prefix ) {
  58069. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  58070. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  58071. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  58072. if ( paddedItemSize % 1 ) {
  58073. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  58074. }
  58075. format = `${prefix}x${paddedItemSize}`;
  58076. }
  58077. }
  58078. if ( ! format ) {
  58079. error( 'WebGPUAttributeUtils: Vertex format not supported yet.' );
  58080. }
  58081. return format;
  58082. }
  58083. /**
  58084. * Utility method for handling interleaved buffer attributes correctly.
  58085. * To process them, their `InterleavedBuffer` is returned.
  58086. *
  58087. * @private
  58088. * @param {BufferAttribute} attribute - The attribute.
  58089. * @return {BufferAttribute|InterleavedBuffer}
  58090. */
  58091. _getBufferAttribute( attribute ) {
  58092. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  58093. return attribute;
  58094. }
  58095. }
  58096. const _bindGroupDescriptor = new GPUBindGroupDescriptor();
  58097. const _bufferDescriptor$2 = new GPUBufferDescriptor();
  58098. const _viewDescriptor$1 = new GPUTextureViewDescriptor();
  58099. /**
  58100. * Class representing a WebGPU bind group layout.
  58101. *
  58102. * @private
  58103. */
  58104. class BindGroupLayout {
  58105. /**
  58106. * Constructs a new layout.
  58107. *
  58108. * @param {GPUBindGroupLayout} layoutGPU - A GPU Bind Group Layout.
  58109. */
  58110. constructor( layoutGPU ) {
  58111. /**
  58112. * The current GPUBindGroupLayout.
  58113. *
  58114. * @type {GPUBindGroupLayout}
  58115. */
  58116. this.layoutGPU = layoutGPU;
  58117. /**
  58118. * The number of bind groups that use this layout.
  58119. *
  58120. * @type {number}
  58121. */
  58122. this.usedTimes = 0;
  58123. }
  58124. }
  58125. /**
  58126. * A WebGPU backend utility module for managing bindings.
  58127. *
  58128. * When reading the documentation it's helpful to keep in mind that
  58129. * all class definitions starting with 'GPU*' are modules from the
  58130. * WebGPU API. So for example `BindGroup` is a class from the engine
  58131. * whereas `GPUBindGroup` is a class from WebGPU.
  58132. *
  58133. * @private
  58134. */
  58135. class WebGPUBindingUtils {
  58136. /**
  58137. * Constructs a new utility object.
  58138. *
  58139. * @param {WebGPUBackend} backend - The WebGPU backend.
  58140. */
  58141. constructor( backend ) {
  58142. /**
  58143. * A reference to the WebGPU backend.
  58144. *
  58145. * @type {WebGPUBackend}
  58146. */
  58147. this.backend = backend;
  58148. /**
  58149. * A cache that maps combinations of layout entries to existing bind group layouts.
  58150. *
  58151. * @private
  58152. * @type {Map<string, BindGroupLayout>}
  58153. */
  58154. this._bindGroupLayoutCache = new Map();
  58155. }
  58156. /**
  58157. * Creates a GPU bind group layout for the given bind group.
  58158. *
  58159. * @param {BindGroup} bindGroup - The bind group.
  58160. * @return {GPUBindGroupLayout} The GPU bind group layout.
  58161. */
  58162. createBindingsLayout( bindGroup ) {
  58163. const backend = this.backend;
  58164. const device = backend.device;
  58165. const bindingsData = backend.get( bindGroup );
  58166. // check if the the bind group already has a layout
  58167. if ( bindingsData.layout ) {
  58168. return bindingsData.layout.layoutGPU;
  58169. }
  58170. // if not, assing one
  58171. const entries = this._createLayoutEntries( bindGroup );
  58172. const bindGroupLayoutKey = hashString( JSON.stringify( entries ) );
  58173. // try to find an existing layout in the cache
  58174. let bindGroupLayout = this._bindGroupLayoutCache.get( bindGroupLayoutKey );
  58175. // if not create a new one
  58176. if ( bindGroupLayout === undefined ) {
  58177. bindGroupLayout = new BindGroupLayout( device.createBindGroupLayout( { entries } ) );
  58178. this._bindGroupLayoutCache.set( bindGroupLayoutKey, bindGroupLayout );
  58179. }
  58180. bindGroupLayout.usedTimes ++;
  58181. bindingsData.layout = bindGroupLayout;
  58182. bindingsData.layoutKey = bindGroupLayoutKey;
  58183. return bindGroupLayout.layoutGPU;
  58184. }
  58185. /**
  58186. * Creates bindings from the given bind group definition.
  58187. *
  58188. * @param {BindGroup} bindGroup - The bind group.
  58189. * @param {Array<BindGroup>} bindings - Array of bind groups.
  58190. * @param {number} cacheIndex - The cache index.
  58191. * @param {number} version - The version.
  58192. */
  58193. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  58194. const { backend } = this;
  58195. const bindingsData = backend.get( bindGroup );
  58196. // setup (static) binding layout and (dynamic) binding group
  58197. const bindLayoutGPU = this.createBindingsLayout( bindGroup );
  58198. let bindGroupGPU;
  58199. if ( cacheIndex > 0 ) {
  58200. if ( bindingsData.groups === undefined ) {
  58201. bindingsData.groups = [];
  58202. bindingsData.versions = [];
  58203. }
  58204. if ( bindingsData.versions[ cacheIndex ] === version ) {
  58205. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  58206. }
  58207. }
  58208. if ( bindGroupGPU === undefined ) {
  58209. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  58210. if ( cacheIndex > 0 ) {
  58211. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  58212. bindingsData.versions[ cacheIndex ] = version;
  58213. }
  58214. }
  58215. bindingsData.group = bindGroupGPU;
  58216. }
  58217. /**
  58218. * Updates a buffer binding.
  58219. *
  58220. * @param {Buffer} binding - The buffer binding to update.
  58221. */
  58222. updateBinding( binding ) {
  58223. const backend = this.backend;
  58224. const device = backend.device;
  58225. const array = binding.buffer; // cpu
  58226. const buffer = backend.get( binding ).buffer; // gpu
  58227. const updateRanges = binding.updateRanges;
  58228. if ( updateRanges.length === 0 ) {
  58229. device.queue.writeBuffer(
  58230. buffer,
  58231. 0,
  58232. array,
  58233. 0
  58234. );
  58235. } else {
  58236. const isTyped = isTypedArray( array );
  58237. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  58238. // Update ranges arrive sorted and non-overlapping which makes
  58239. // it easy to merge contiguous ranges.
  58240. let start = updateRanges[ 0 ].start; // start of the current merged range
  58241. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  58242. const range = updateRanges[ i ];
  58243. const next = updateRanges[ i + 1 ];
  58244. const end = range.start + range.count; // exclusive end of the current range
  58245. // keep merging while the next range is contiguous
  58246. if ( next !== undefined && next.start === end ) continue;
  58247. // write the merged range
  58248. const dataOffset = start * byteOffsetFactor;
  58249. const size = ( end - start ) * byteOffsetFactor;
  58250. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  58251. device.queue.writeBuffer(
  58252. buffer,
  58253. bufferOffset,
  58254. array,
  58255. dataOffset,
  58256. size
  58257. );
  58258. // start next if possible
  58259. if ( next !== undefined ) start = next.start;
  58260. }
  58261. }
  58262. }
  58263. /**
  58264. * Creates a GPU bind group for the camera index.
  58265. *
  58266. * @param {Uint32Array} data - The index data.
  58267. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  58268. * @return {GPUBindGroup} The GPU bind group.
  58269. */
  58270. createBindGroupIndex( data, layoutGPU ) {
  58271. const backend = this.backend;
  58272. const device = backend.device;
  58273. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  58274. const index = data[ 0 ];
  58275. _bufferDescriptor$2.label = 'bindingCameraIndex_' + index;
  58276. _bufferDescriptor$2.size = 16; // uint(4) * 4
  58277. _bufferDescriptor$2.usage = usage;
  58278. const buffer = device.createBuffer( _bufferDescriptor$2 );
  58279. _bufferDescriptor$2.reset();
  58280. device.queue.writeBuffer( buffer, 0, data, 0 );
  58281. _bindGroupDescriptor.label = 'bindGroupCameraIndex_' + index;
  58282. _bindGroupDescriptor.layout = layoutGPU;
  58283. _bindGroupDescriptor.entries.push( { binding: 0, resource: { buffer } } );
  58284. const bindGroup = device.createBindGroup( _bindGroupDescriptor );
  58285. _bindGroupDescriptor.reset();
  58286. return bindGroup;
  58287. }
  58288. /**
  58289. * Creates a GPU bind group for the given bind group and GPU layout.
  58290. *
  58291. * @param {BindGroup} bindGroup - The bind group.
  58292. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  58293. * @return {GPUBindGroup} The GPU bind group.
  58294. */
  58295. createBindGroup( bindGroup, layoutGPU ) {
  58296. const backend = this.backend;
  58297. const device = backend.device;
  58298. let bindingPoint = 0;
  58299. _bindGroupDescriptor.label = 'bindGroup_' + bindGroup.name;
  58300. _bindGroupDescriptor.layout = layoutGPU;
  58301. for ( const binding of bindGroup.bindings ) {
  58302. if ( binding.isUniformBuffer ) {
  58303. const bindingData = backend.get( binding );
  58304. _bindGroupDescriptor.entries.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  58305. } else if ( binding.isStorageBuffer ) {
  58306. const buffer = backend.get( binding.attribute ).buffer;
  58307. _bindGroupDescriptor.entries.push( { binding: bindingPoint, resource: { buffer: buffer } } );
  58308. } else if ( binding.isSampledTexture ) {
  58309. const textureData = backend.get( binding.texture );
  58310. let resourceGPU;
  58311. if ( textureData.externalTexture !== undefined ) {
  58312. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  58313. } else {
  58314. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  58315. const baseMipLevel = binding.store ? binding.mipLevel : 0;
  58316. let propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }`;
  58317. if ( textureData.texture.depthOrArrayLayers > 1 ) {
  58318. propertyName += `-${ textureData.texture.depthOrArrayLayers }`;
  58319. }
  58320. propertyName += `-${ mipLevelCount }-${ baseMipLevel }`;
  58321. resourceGPU = textureData[ propertyName ];
  58322. if ( resourceGPU === undefined ) {
  58323. const aspectGPU = GPUTextureAspect.All;
  58324. let dimensionViewGPU;
  58325. if ( binding.isSampledCubeTexture ) {
  58326. dimensionViewGPU = GPUTextureViewDimension.Cube;
  58327. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  58328. // Prefer the texture's actual array flag over the cached 3D binding type.
  58329. // Layered render targets can become array textures after shader compilation.
  58330. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  58331. } else if ( binding.isSampledTexture3D ) {
  58332. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  58333. } else {
  58334. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  58335. }
  58336. _viewDescriptor$1.aspect = aspectGPU;
  58337. _viewDescriptor$1.dimension = dimensionViewGPU;
  58338. _viewDescriptor$1.mipLevelCount = mipLevelCount;
  58339. _viewDescriptor$1.baseMipLevel = baseMipLevel;
  58340. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( _viewDescriptor$1 );
  58341. _viewDescriptor$1.reset();
  58342. }
  58343. }
  58344. _bindGroupDescriptor.entries.push( { binding: bindingPoint, resource: resourceGPU } );
  58345. } else if ( binding.isSampler ) {
  58346. const bindingData = backend.get( binding );
  58347. _bindGroupDescriptor.entries.push( { binding: bindingPoint, resource: bindingData.sampler } );
  58348. }
  58349. bindingPoint ++;
  58350. }
  58351. const bindGroupGPU = device.createBindGroup( _bindGroupDescriptor );
  58352. _bindGroupDescriptor.reset();
  58353. return bindGroupGPU;
  58354. }
  58355. /**
  58356. * Creates a GPU bind group layout entries for the given bind group.
  58357. *
  58358. * @private
  58359. * @param {BindGroup} bindGroup - The bind group.
  58360. * @return {Array<GPUBindGroupLayoutEntry>} The GPU bind group layout entries.
  58361. */
  58362. _createLayoutEntries( bindGroup ) {
  58363. const entries = [];
  58364. let index = 0;
  58365. for ( const binding of bindGroup.bindings ) {
  58366. const backend = this.backend;
  58367. const bindingGPU = {
  58368. binding: index,
  58369. visibility: binding.visibility
  58370. };
  58371. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  58372. const buffer = {}; // GPUBufferBindingLayout
  58373. if ( binding.isStorageBuffer ) {
  58374. if ( binding.visibility & GPUShaderStage.COMPUTE ) {
  58375. // compute
  58376. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  58377. buffer.type = GPUBufferBindingType.Storage;
  58378. } else {
  58379. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  58380. }
  58381. } else {
  58382. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  58383. }
  58384. }
  58385. bindingGPU.buffer = buffer;
  58386. } else if ( binding.isSampledTexture && binding.store ) {
  58387. const storageTexture = {}; // GPUStorageTextureBindingLayout
  58388. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  58389. const access = binding.access;
  58390. if ( access === NodeAccess.READ_WRITE ) {
  58391. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  58392. } else if ( access === NodeAccess.WRITE_ONLY ) {
  58393. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  58394. } else {
  58395. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  58396. }
  58397. if ( binding.texture.isArrayTexture ) {
  58398. storageTexture.viewDimension = GPUTextureViewDimension.TwoDArray;
  58399. } else if ( binding.texture.is3DTexture ) {
  58400. storageTexture.viewDimension = GPUTextureViewDimension.ThreeD;
  58401. }
  58402. bindingGPU.storageTexture = storageTexture;
  58403. } else if ( binding.isSampledTexture ) {
  58404. const texture = {}; // GPUTextureBindingLayout
  58405. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  58406. if ( primarySamples > 1 ) {
  58407. texture.multisampled = true;
  58408. if ( ! binding.texture.isDepthTexture ) {
  58409. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  58410. }
  58411. }
  58412. if ( binding.texture.isDepthTexture ) {
  58413. if ( backend.compatibilityMode && binding.texture.compareFunction === null ) {
  58414. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  58415. } else {
  58416. texture.sampleType = GPUTextureSampleType.Depth;
  58417. }
  58418. } else {
  58419. const type = binding.texture.type;
  58420. if ( type === IntType ) {
  58421. texture.sampleType = GPUTextureSampleType.SInt;
  58422. } else if ( type === UnsignedIntType ) {
  58423. texture.sampleType = GPUTextureSampleType.UInt;
  58424. } else if ( binding.texture.normalized === true && ( type === ShortType || type === UnsignedShortType ) ) {
  58425. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  58426. } else if ( type === FloatType ) {
  58427. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  58428. texture.sampleType = GPUTextureSampleType.Float;
  58429. } else {
  58430. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  58431. }
  58432. }
  58433. }
  58434. if ( binding.isSampledCubeTexture ) {
  58435. texture.viewDimension = GPUTextureViewDimension.Cube;
  58436. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  58437. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  58438. } else if ( binding.isSampledTexture3D ) {
  58439. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  58440. }
  58441. bindingGPU.texture = texture;
  58442. } else if ( binding.isSampler ) {
  58443. const sampler = {}; // GPUSamplerBindingLayout
  58444. if ( binding.texture.isDepthTexture ) {
  58445. if ( binding.texture.compareFunction !== null && binding.textureNode.compareNode !== null && backend.hasCompatibility( Compatibility.TEXTURE_COMPARE ) ) {
  58446. sampler.type = GPUSamplerBindingType.Comparison;
  58447. } else {
  58448. // Depth textures without compare must use non-filtering sampler
  58449. sampler.type = GPUSamplerBindingType.NonFiltering;
  58450. }
  58451. }
  58452. bindingGPU.sampler = sampler;
  58453. } else {
  58454. error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  58455. }
  58456. entries.push( bindingGPU );
  58457. index ++;
  58458. }
  58459. return entries;
  58460. }
  58461. /**
  58462. * Delete the data associated with a bind group.
  58463. *
  58464. * @param {BindGroup} bindGroup - The bind group.
  58465. */
  58466. deleteBindGroupData( bindGroup ) {
  58467. const { backend } = this;
  58468. const bindingsData = backend.get( bindGroup );
  58469. if ( bindingsData.layout ) {
  58470. bindingsData.layout.usedTimes --;
  58471. if ( bindingsData.layout.usedTimes === 0 ) {
  58472. this._bindGroupLayoutCache.delete( bindingsData.layoutKey );
  58473. }
  58474. bindingsData.layout = undefined;
  58475. bindingsData.layoutKey = undefined;
  58476. }
  58477. }
  58478. /**
  58479. * Frees internal resources.
  58480. */
  58481. dispose() {
  58482. this._bindGroupLayoutCache.clear();
  58483. }
  58484. }
  58485. /**
  58486. * A WebGPU backend utility module for managing the device's capabilities.
  58487. *
  58488. * @private
  58489. */
  58490. class WebGPUCapabilities {
  58491. /**
  58492. * Constructs a new utility object.
  58493. *
  58494. * @param {WebGPUBackend} backend - The WebGPU backend.
  58495. */
  58496. constructor( backend ) {
  58497. /**
  58498. * A reference to the WebGPU backend.
  58499. *
  58500. * @type {WebGPUBackend}
  58501. */
  58502. this.backend = backend;
  58503. }
  58504. /**
  58505. * Returns the maximum anisotropy texture filtering value.
  58506. *
  58507. * @return {number} The maximum anisotropy texture filtering value.
  58508. */
  58509. getMaxAnisotropy() {
  58510. return 16;
  58511. }
  58512. /**
  58513. * Returns the maximum number of bytes available for uniform buffers.
  58514. *
  58515. * @return {number} The maximum number of bytes available for uniform buffers.
  58516. */
  58517. getUniformBufferLimit() {
  58518. return this.backend.device.limits.maxUniformBufferBindingSize;
  58519. }
  58520. }
  58521. /**
  58522. * Reusable descriptor for `GPUDevice.createComputePipeline()`.
  58523. *
  58524. * @private
  58525. */
  58526. class GPUComputePipelineDescriptor {
  58527. constructor() {
  58528. /**
  58529. * The label of the compute pipeline.
  58530. *
  58531. * @type {string}
  58532. */
  58533. this.label = '';
  58534. /**
  58535. * The pipeline layout the pipeline conforms to, or `'auto'`.
  58536. *
  58537. * @type {?GPUPipelineLayout|string}
  58538. * @default null
  58539. */
  58540. this.layout = null;
  58541. /**
  58542. * The programmable compute stage.
  58543. *
  58544. * @type {?Object}
  58545. * @default null
  58546. */
  58547. this.compute = null;
  58548. }
  58549. /**
  58550. * Resets the descriptor to its default state.
  58551. */
  58552. reset() {
  58553. this.label = '';
  58554. this.layout = null;
  58555. this.compute = null;
  58556. }
  58557. }
  58558. /**
  58559. * Reusable descriptor for `GPUDevice.createPipelineLayout()`.
  58560. *
  58561. * @private
  58562. */
  58563. class GPUPipelineLayoutDescriptor {
  58564. constructor() {
  58565. /**
  58566. * The label of the pipeline layout.
  58567. *
  58568. * @type {string}
  58569. */
  58570. this.label = '';
  58571. /**
  58572. * The set of bind group layouts the pipeline layout describes.
  58573. *
  58574. * @type {?Array<?GPUBindGroupLayout>}
  58575. * @default null
  58576. */
  58577. this.bindGroupLayouts = null;
  58578. }
  58579. /**
  58580. * Resets the descriptor to its default state.
  58581. */
  58582. reset() {
  58583. this.label = '';
  58584. this.bindGroupLayouts = null;
  58585. }
  58586. }
  58587. const _computePipelineDescriptor = new GPUComputePipelineDescriptor();
  58588. const _pipelineLayoutDescriptor = new GPUPipelineLayoutDescriptor();
  58589. const _renderBundleEncoderDescriptor = new GPURenderBundleEncoderDescriptor();
  58590. const _renderPipelineDescriptor = new GPURenderPipelineDescriptor();
  58591. /**
  58592. * A WebGPU backend utility module for managing pipelines.
  58593. *
  58594. * @private
  58595. */
  58596. class WebGPUPipelineUtils {
  58597. /**
  58598. * Constructs a new utility object.
  58599. *
  58600. * @param {WebGPUBackend} backend - The WebGPU backend.
  58601. */
  58602. constructor( backend ) {
  58603. /**
  58604. * A reference to the WebGPU backend.
  58605. *
  58606. * @type {WebGPUBackend}
  58607. */
  58608. this.backend = backend;
  58609. }
  58610. /**
  58611. * Returns the sample count derived from the given render context.
  58612. *
  58613. * @private
  58614. * @param {RenderContext} renderContext - The render context.
  58615. * @return {number} The sample count.
  58616. */
  58617. _getSampleCount( renderContext ) {
  58618. return this.backend.utils.getSampleCountRenderContext( renderContext );
  58619. }
  58620. /**
  58621. * Creates a render pipeline for the given render object.
  58622. *
  58623. * @param {RenderObject} renderObject - The render object.
  58624. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  58625. */
  58626. createRenderPipeline( renderObject, promises ) {
  58627. const { object, material, geometry, pipeline } = renderObject;
  58628. const { vertexProgram, fragmentProgram } = pipeline;
  58629. const backend = this.backend;
  58630. const device = backend.device;
  58631. const utils = backend.utils;
  58632. const pipelineData = backend.get( pipeline );
  58633. // bind group layouts
  58634. const bindGroupLayouts = [];
  58635. for ( const bindGroup of renderObject.getBindings() ) {
  58636. const bindingsData = backend.get( bindGroup );
  58637. const { layoutGPU } = bindingsData.layout;
  58638. bindGroupLayouts.push( layoutGPU );
  58639. }
  58640. // vertex buffers
  58641. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  58642. // material blending
  58643. let materialBlending;
  58644. if ( material.blending !== NoBlending && ( material.blending !== NormalBlending || material.transparent !== false ) ) {
  58645. materialBlending = this._getBlending( material );
  58646. }
  58647. // stencil
  58648. let stencilFront = {};
  58649. if ( material.stencilWrite === true ) {
  58650. stencilFront = {
  58651. compare: this._getStencilCompare( material ),
  58652. failOp: this._getStencilOperation( material.stencilFail ),
  58653. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  58654. passOp: this._getStencilOperation( material.stencilZPass )
  58655. };
  58656. }
  58657. const colorWriteMask = this._getColorWriteMask( material );
  58658. const targets = [];
  58659. if ( renderObject.context.textures !== null ) {
  58660. const textures = renderObject.context.textures;
  58661. const mrt = renderObject.context.mrt;
  58662. for ( let i = 0; i < textures.length; i ++ ) {
  58663. const texture = textures[ i ];
  58664. const colorFormat = utils.getTextureFormatGPU( texture );
  58665. // mrt blending
  58666. let blending;
  58667. if ( mrt !== null ) {
  58668. if ( this.backend.compatibilityMode !== true ) {
  58669. const blendMode = mrt.getBlendMode( texture.name );
  58670. if ( blendMode.blending === MaterialBlending ) {
  58671. blending = materialBlending;
  58672. } else if ( blendMode.blending !== NoBlending ) {
  58673. blending = this._getBlending( blendMode );
  58674. }
  58675. } else {
  58676. warnOnce( 'WebGPURenderer: Multiple Render Targets (MRT) blending configuration is not fully supported in compatibility mode. The material blending will be used for all render targets.' );
  58677. blending = materialBlending;
  58678. }
  58679. } else {
  58680. blending = materialBlending;
  58681. }
  58682. targets.push( {
  58683. format: colorFormat,
  58684. blend: blending,
  58685. writeMask: colorWriteMask
  58686. } );
  58687. }
  58688. } else {
  58689. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  58690. targets.push( {
  58691. format: colorFormat,
  58692. blend: materialBlending,
  58693. writeMask: colorWriteMask
  58694. } );
  58695. }
  58696. const vertexModule = backend.get( vertexProgram ).module;
  58697. const fragmentModule = backend.get( fragmentProgram ).module;
  58698. const primitiveState = this._getPrimitiveState( object, geometry, material );
  58699. const depthCompare = this._getDepthCompare( material );
  58700. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  58701. const sampleCount = this._getSampleCount( renderObject.context );
  58702. _pipelineLayoutDescriptor.bindGroupLayouts = bindGroupLayouts;
  58703. const pipelineLayout = device.createPipelineLayout( _pipelineLayoutDescriptor );
  58704. _pipelineLayoutDescriptor.reset();
  58705. _renderPipelineDescriptor.label = `renderPipeline_${ material.name || material.type }_${ material.id }`;
  58706. _renderPipelineDescriptor.vertex = Object.assign( {}, vertexModule, { buffers: vertexBuffers } );
  58707. _renderPipelineDescriptor.fragment = Object.assign( {}, fragmentModule, { targets } );
  58708. _renderPipelineDescriptor.primitive = primitiveState;
  58709. _renderPipelineDescriptor.multisample.count = sampleCount;
  58710. _renderPipelineDescriptor.multisample.alphaToCoverageEnabled = material.alphaToCoverage && sampleCount > 1;
  58711. _renderPipelineDescriptor.layout = pipelineLayout;
  58712. const depthStencil = {};
  58713. const renderDepth = renderObject.context.depth;
  58714. const renderStencil = renderObject.context.stencil;
  58715. if ( renderDepth === true || renderStencil === true ) {
  58716. if ( renderDepth === true ) {
  58717. depthStencil.format = depthStencilFormat;
  58718. depthStencil.depthWriteEnabled = material.depthWrite;
  58719. depthStencil.depthCompare = depthCompare;
  58720. }
  58721. if ( renderStencil === true ) {
  58722. depthStencil.stencilFront = stencilFront;
  58723. depthStencil.stencilBack = stencilFront; // apply the same stencil ops to both faces, matching gl.stencilOp() which is not face-separated
  58724. depthStencil.stencilReadMask = material.stencilFuncMask;
  58725. depthStencil.stencilWriteMask = material.stencilWriteMask;
  58726. }
  58727. if ( material.polygonOffset === true && ( primitiveState.topology === GPUPrimitiveTopology.TriangleList ) ) {
  58728. depthStencil.depthBias = material.polygonOffsetUnits;
  58729. depthStencil.depthBiasSlopeScale = material.polygonOffsetFactor;
  58730. depthStencil.depthBiasClamp = 0; // three.js does not provide an API to configure this value
  58731. }
  58732. _renderPipelineDescriptor.depthStencil = depthStencil;
  58733. }
  58734. // create pipeline
  58735. device.pushErrorScope( 'validation' );
  58736. const stages = [
  58737. { program: vertexProgram, module: vertexModule.module },
  58738. { program: fragmentProgram, module: fragmentModule.module }
  58739. ];
  58740. const pipelineLabel = _renderPipelineDescriptor.label;
  58741. if ( promises === null ) {
  58742. pipelineData.pipeline = device.createRenderPipeline( _renderPipelineDescriptor );
  58743. _renderPipelineDescriptor.reset();
  58744. device.popErrorScope().then( ( err ) => {
  58745. if ( err !== null ) {
  58746. pipelineData.error = true;
  58747. error( `WebGPURenderer: Render pipeline creation failed (${ pipelineLabel }): ${ err.message }` );
  58748. this._reportShaderDiagnostics( stages, pipelineLabel );
  58749. }
  58750. } );
  58751. } else {
  58752. const p = new Promise( async ( resolve /*, reject*/ ) => {
  58753. try {
  58754. let asyncError = null;
  58755. let pipelinePromise = null;
  58756. try {
  58757. pipelinePromise = device.createRenderPipelineAsync( _renderPipelineDescriptor );
  58758. } catch ( err ) {
  58759. asyncError = err;
  58760. }
  58761. _renderPipelineDescriptor.reset();
  58762. if ( pipelinePromise !== null ) {
  58763. try {
  58764. pipelineData.pipeline = await pipelinePromise;
  58765. } catch ( err ) {
  58766. asyncError = err;
  58767. }
  58768. }
  58769. const errorScope = await device.popErrorScope();
  58770. if ( errorScope !== null || asyncError !== null ) {
  58771. pipelineData.error = true;
  58772. const reason = ( errorScope && errorScope.message ) || ( asyncError && asyncError.message ) || 'unknown';
  58773. error( `WebGPURenderer: Async render pipeline creation failed (${ pipelineLabel }): ${ reason }` );
  58774. await this._reportShaderDiagnostics( stages, pipelineLabel );
  58775. }
  58776. } finally {
  58777. // Guarantee resolution so `compileAsync`'s Promise.all cannot hang on an
  58778. // unexpected throw from any await above.
  58779. resolve();
  58780. }
  58781. } );
  58782. promises.push( p );
  58783. }
  58784. }
  58785. /**
  58786. * Creates GPU render bundle encoder for the given render context.
  58787. *
  58788. * @param {RenderContext} renderContext - The render context.
  58789. * @param {?string} [label='renderBundleEncoder'] - The label.
  58790. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  58791. */
  58792. createBundleEncoder( renderContext, label = 'renderBundleEncoder' ) {
  58793. const backend = this.backend;
  58794. const { utils, device } = backend;
  58795. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  58796. const colorFormats = utils.getCurrentColorFormats( renderContext );
  58797. const sampleCount = this._getSampleCount( renderContext );
  58798. _renderBundleEncoderDescriptor.label = label;
  58799. _renderBundleEncoderDescriptor.colorFormats = colorFormats;
  58800. _renderBundleEncoderDescriptor.depthStencilFormat = depthStencilFormat;
  58801. _renderBundleEncoderDescriptor.sampleCount = sampleCount;
  58802. const bundleEncoder = device.createRenderBundleEncoder( _renderBundleEncoderDescriptor );
  58803. _renderBundleEncoderDescriptor.reset();
  58804. return bundleEncoder;
  58805. }
  58806. /**
  58807. * Creates a compute pipeline for the given compute node.
  58808. *
  58809. * @param {ComputePipeline} pipeline - The compute pipeline.
  58810. * @param {Array<BindGroup>} bindings - The bindings.
  58811. */
  58812. createComputePipeline( pipeline, bindings ) {
  58813. const backend = this.backend;
  58814. const device = backend.device;
  58815. const computeProgram = backend.get( pipeline.computeProgram ).module;
  58816. const pipelineGPU = backend.get( pipeline );
  58817. // bind group layouts
  58818. const bindGroupLayouts = [];
  58819. for ( const bindingsGroup of bindings ) {
  58820. const bindingsData = backend.get( bindingsGroup );
  58821. const { layoutGPU } = bindingsData.layout;
  58822. bindGroupLayouts.push( layoutGPU );
  58823. }
  58824. const computeStage = pipeline.computeProgram;
  58825. const pipelineLabel = `computePipeline_${ computeStage.stage }${ computeStage.name ? `_${ computeStage.name }` : '' }`;
  58826. device.pushErrorScope( 'validation' );
  58827. _pipelineLayoutDescriptor.bindGroupLayouts = bindGroupLayouts;
  58828. const pipelineLayout = device.createPipelineLayout( _pipelineLayoutDescriptor );
  58829. _pipelineLayoutDescriptor.reset();
  58830. _computePipelineDescriptor.label = pipelineLabel;
  58831. _computePipelineDescriptor.compute = computeProgram;
  58832. _computePipelineDescriptor.layout = pipelineLayout;
  58833. pipelineGPU.pipeline = device.createComputePipeline( _computePipelineDescriptor );
  58834. _computePipelineDescriptor.reset();
  58835. device.popErrorScope().then( ( err ) => {
  58836. if ( err !== null ) {
  58837. pipelineGPU.error = true;
  58838. error( `WebGPURenderer: Compute pipeline creation failed (${ pipelineLabel }): ${ err.message }` );
  58839. this._reportShaderDiagnostics( [ { program: computeStage, module: computeProgram.module } ], pipelineLabel );
  58840. }
  58841. } );
  58842. }
  58843. /**
  58844. * Reads line-accurate diagnostics from shader modules and logs them.
  58845. * Called from pipeline creation error paths to turn opaque validation
  58846. * failures into actionable WGSL feedback.
  58847. *
  58848. * @private
  58849. * @param {Array<{program: ProgrammableStage, module: GPUShaderModule}>} stages - Pairs of program + compiled shader module.
  58850. * @param {string} pipelineLabel - Label of the owning pipeline, used as log prefix.
  58851. * @return {Promise<void>}
  58852. */
  58853. async _reportShaderDiagnostics( stages, pipelineLabel ) {
  58854. for ( const { program, module } of stages ) {
  58855. const info = await module.getCompilationInfo();
  58856. if ( info.messages.length === 0 ) continue;
  58857. const sourceLines = program.code.split( '\n' );
  58858. for ( const msg of info.messages ) {
  58859. const location = msg.lineNum > 0
  58860. ? ` at line ${ msg.lineNum }${ msg.linePos > 0 ? `:${ msg.linePos }` : '' }`
  58861. : '';
  58862. const header = `WebGPURenderer [${ pipelineLabel } / ${ program.stage } ${ msg.type }]${ location }: ${ msg.message }`;
  58863. let excerpt = '';
  58864. if ( msg.lineNum > 0 && msg.lineNum <= sourceLines.length ) {
  58865. excerpt = `\n ${ sourceLines[ msg.lineNum - 1 ] }`;
  58866. if ( msg.linePos > 0 ) excerpt += `\n ${ ' '.repeat( msg.linePos - 1 ) }^`;
  58867. }
  58868. ( msg.type === 'error' ? error : warn )( header + excerpt );
  58869. }
  58870. }
  58871. }
  58872. /**
  58873. * Returns the blending state as a descriptor object required
  58874. * for the pipeline creation.
  58875. *
  58876. * @private
  58877. * @param {Material|BlendMode} object - The object containing blending information.
  58878. * @return {Object} The blending state.
  58879. */
  58880. _getBlending( object ) {
  58881. let color, alpha;
  58882. const blending = object.blending;
  58883. const blendSrc = object.blendSrc;
  58884. const blendDst = object.blendDst;
  58885. const blendEquation = object.blendEquation;
  58886. if ( blending === CustomBlending ) {
  58887. const blendSrcAlpha = object.blendSrcAlpha !== null ? object.blendSrcAlpha : blendSrc;
  58888. const blendDstAlpha = object.blendDstAlpha !== null ? object.blendDstAlpha : blendDst;
  58889. const blendEquationAlpha = object.blendEquationAlpha !== null ? object.blendEquationAlpha : blendEquation;
  58890. color = {
  58891. srcFactor: this._getBlendFactor( blendSrc ),
  58892. dstFactor: this._getBlendFactor( blendDst ),
  58893. operation: this._getBlendOperation( blendEquation )
  58894. };
  58895. alpha = {
  58896. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  58897. dstFactor: this._getBlendFactor( blendDstAlpha ),
  58898. operation: this._getBlendOperation( blendEquationAlpha )
  58899. };
  58900. } else {
  58901. const premultipliedAlpha = object.premultipliedAlpha;
  58902. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  58903. color = {
  58904. srcFactor: srcRGB,
  58905. dstFactor: dstRGB,
  58906. operation: GPUBlendOperation.Add
  58907. };
  58908. alpha = {
  58909. srcFactor: srcAlpha,
  58910. dstFactor: dstAlpha,
  58911. operation: GPUBlendOperation.Add
  58912. };
  58913. };
  58914. if ( premultipliedAlpha ) {
  58915. switch ( blending ) {
  58916. case NormalBlending:
  58917. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  58918. break;
  58919. case AdditiveBlending:
  58920. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  58921. break;
  58922. case SubtractiveBlending:
  58923. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  58924. break;
  58925. case MultiplyBlending:
  58926. setBlend( GPUBlendFactor.Dst, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.Zero, GPUBlendFactor.One );
  58927. break;
  58928. }
  58929. } else {
  58930. switch ( blending ) {
  58931. case NormalBlending:
  58932. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  58933. break;
  58934. case AdditiveBlending:
  58935. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  58936. break;
  58937. case SubtractiveBlending:
  58938. error( `WebGPURenderer: "SubtractiveBlending" requires "${ object.isMaterial ? 'material' : 'blendMode' }.premultipliedAlpha = true".` );
  58939. break;
  58940. case MultiplyBlending:
  58941. error( `WebGPURenderer: "MultiplyBlending" requires "${ object.isMaterial ? 'material' : 'blendMode' }.premultipliedAlpha = true".` );
  58942. break;
  58943. }
  58944. }
  58945. }
  58946. if ( color !== undefined && alpha !== undefined ) {
  58947. return { color, alpha };
  58948. } else {
  58949. error( 'WebGPURenderer: Invalid blending: ', blending );
  58950. }
  58951. }
  58952. /**
  58953. * Returns the GPU blend factor which is required for the pipeline creation.
  58954. *
  58955. * @private
  58956. * @param {number} blend - The blend factor as a three.js constant.
  58957. * @return {string} The GPU blend factor.
  58958. */
  58959. _getBlendFactor( blend ) {
  58960. let blendFactor;
  58961. switch ( blend ) {
  58962. case ZeroFactor:
  58963. blendFactor = GPUBlendFactor.Zero;
  58964. break;
  58965. case OneFactor:
  58966. blendFactor = GPUBlendFactor.One;
  58967. break;
  58968. case SrcColorFactor:
  58969. blendFactor = GPUBlendFactor.Src;
  58970. break;
  58971. case OneMinusSrcColorFactor:
  58972. blendFactor = GPUBlendFactor.OneMinusSrc;
  58973. break;
  58974. case SrcAlphaFactor:
  58975. blendFactor = GPUBlendFactor.SrcAlpha;
  58976. break;
  58977. case OneMinusSrcAlphaFactor:
  58978. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  58979. break;
  58980. case DstColorFactor:
  58981. blendFactor = GPUBlendFactor.Dst;
  58982. break;
  58983. case OneMinusDstColorFactor:
  58984. blendFactor = GPUBlendFactor.OneMinusDst;
  58985. break;
  58986. case DstAlphaFactor:
  58987. blendFactor = GPUBlendFactor.DstAlpha;
  58988. break;
  58989. case OneMinusDstAlphaFactor:
  58990. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  58991. break;
  58992. case SrcAlphaSaturateFactor:
  58993. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  58994. break;
  58995. case BlendColorFactor:
  58996. blendFactor = GPUBlendFactor.Constant;
  58997. break;
  58998. case OneMinusBlendColorFactor:
  58999. blendFactor = GPUBlendFactor.OneMinusConstant;
  59000. break;
  59001. default:
  59002. error( 'WebGPURenderer: Blend factor not supported.', blend );
  59003. }
  59004. return blendFactor;
  59005. }
  59006. /**
  59007. * Returns the GPU stencil compare function which is required for the pipeline creation.
  59008. *
  59009. * @private
  59010. * @param {Material} material - The material.
  59011. * @return {string} The GPU stencil compare function.
  59012. */
  59013. _getStencilCompare( material ) {
  59014. let stencilCompare;
  59015. const stencilFunc = material.stencilFunc;
  59016. switch ( stencilFunc ) {
  59017. case NeverStencilFunc:
  59018. stencilCompare = GPUCompareFunction.Never;
  59019. break;
  59020. case AlwaysStencilFunc:
  59021. stencilCompare = GPUCompareFunction.Always;
  59022. break;
  59023. case LessStencilFunc:
  59024. stencilCompare = GPUCompareFunction.Less;
  59025. break;
  59026. case LessEqualStencilFunc:
  59027. stencilCompare = GPUCompareFunction.LessEqual;
  59028. break;
  59029. case EqualStencilFunc:
  59030. stencilCompare = GPUCompareFunction.Equal;
  59031. break;
  59032. case GreaterEqualStencilFunc:
  59033. stencilCompare = GPUCompareFunction.GreaterEqual;
  59034. break;
  59035. case GreaterStencilFunc:
  59036. stencilCompare = GPUCompareFunction.Greater;
  59037. break;
  59038. case NotEqualStencilFunc:
  59039. stencilCompare = GPUCompareFunction.NotEqual;
  59040. break;
  59041. default:
  59042. error( 'WebGPURenderer: Invalid stencil function.', stencilFunc );
  59043. }
  59044. return stencilCompare;
  59045. }
  59046. /**
  59047. * Returns the GPU stencil operation which is required for the pipeline creation.
  59048. *
  59049. * @private
  59050. * @param {number} op - A three.js constant defining the stencil operation.
  59051. * @return {string} The GPU stencil operation.
  59052. */
  59053. _getStencilOperation( op ) {
  59054. let stencilOperation;
  59055. switch ( op ) {
  59056. case KeepStencilOp:
  59057. stencilOperation = GPUStencilOperation.Keep;
  59058. break;
  59059. case ZeroStencilOp:
  59060. stencilOperation = GPUStencilOperation.Zero;
  59061. break;
  59062. case ReplaceStencilOp:
  59063. stencilOperation = GPUStencilOperation.Replace;
  59064. break;
  59065. case InvertStencilOp:
  59066. stencilOperation = GPUStencilOperation.Invert;
  59067. break;
  59068. case IncrementStencilOp:
  59069. stencilOperation = GPUStencilOperation.IncrementClamp;
  59070. break;
  59071. case DecrementStencilOp:
  59072. stencilOperation = GPUStencilOperation.DecrementClamp;
  59073. break;
  59074. case IncrementWrapStencilOp:
  59075. stencilOperation = GPUStencilOperation.IncrementWrap;
  59076. break;
  59077. case DecrementWrapStencilOp:
  59078. stencilOperation = GPUStencilOperation.DecrementWrap;
  59079. break;
  59080. default:
  59081. error( 'WebGPURenderer: Invalid stencil operation.', stencilOperation );
  59082. }
  59083. return stencilOperation;
  59084. }
  59085. /**
  59086. * Returns the GPU blend operation which is required for the pipeline creation.
  59087. *
  59088. * @private
  59089. * @param {number} blendEquation - A three.js constant defining the blend equation.
  59090. * @return {string} The GPU blend operation.
  59091. */
  59092. _getBlendOperation( blendEquation ) {
  59093. let blendOperation;
  59094. switch ( blendEquation ) {
  59095. case AddEquation:
  59096. blendOperation = GPUBlendOperation.Add;
  59097. break;
  59098. case SubtractEquation:
  59099. blendOperation = GPUBlendOperation.Subtract;
  59100. break;
  59101. case ReverseSubtractEquation:
  59102. blendOperation = GPUBlendOperation.ReverseSubtract;
  59103. break;
  59104. case MinEquation:
  59105. blendOperation = GPUBlendOperation.Min;
  59106. break;
  59107. case MaxEquation:
  59108. blendOperation = GPUBlendOperation.Max;
  59109. break;
  59110. default:
  59111. error( 'WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  59112. }
  59113. return blendOperation;
  59114. }
  59115. /**
  59116. * Returns the primitive state as a descriptor object required
  59117. * for the pipeline creation.
  59118. *
  59119. * @private
  59120. * @param {Object3D} object - The 3D object.
  59121. * @param {BufferGeometry} geometry - The geometry.
  59122. * @param {Material} material - The material.
  59123. * @return {Object} The primitive state.
  59124. */
  59125. _getPrimitiveState( object, geometry, material ) {
  59126. const descriptor = {};
  59127. const utils = this.backend.utils;
  59128. //
  59129. descriptor.topology = utils.getPrimitiveTopology( object, material );
  59130. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  59131. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  59132. }
  59133. //
  59134. let flipSided = ( material.side === BackSide );
  59135. if ( object.isMesh && object.matrixWorld.determinantAffine() < 0 ) flipSided = ! flipSided;
  59136. descriptor.frontFace = ( flipSided === true ) ? GPUFrontFace.CW : GPUFrontFace.CCW;
  59137. //
  59138. descriptor.cullMode = ( material.side === DoubleSide ) ? GPUCullMode.None : GPUCullMode.Back;
  59139. return descriptor;
  59140. }
  59141. /**
  59142. * Returns the GPU color write mask which is required for the pipeline creation.
  59143. *
  59144. * @private
  59145. * @param {Material} material - The material.
  59146. * @return {number} The GPU color write mask.
  59147. */
  59148. _getColorWriteMask( material ) {
  59149. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  59150. }
  59151. /**
  59152. * Returns the GPU depth compare function which is required for the pipeline creation.
  59153. *
  59154. * @private
  59155. * @param {Material} material - The material.
  59156. * @return {string} The GPU depth compare function.
  59157. */
  59158. _getDepthCompare( material ) {
  59159. let depthCompare;
  59160. if ( material.depthTest === false ) {
  59161. depthCompare = GPUCompareFunction.Always;
  59162. } else {
  59163. const depthFunc = ( this.backend.parameters.reversedDepthBuffer ) ? ReversedDepthFuncs[ material.depthFunc ] : material.depthFunc;
  59164. switch ( depthFunc ) {
  59165. case NeverDepth:
  59166. depthCompare = GPUCompareFunction.Never;
  59167. break;
  59168. case AlwaysDepth:
  59169. depthCompare = GPUCompareFunction.Always;
  59170. break;
  59171. case LessDepth:
  59172. depthCompare = GPUCompareFunction.Less;
  59173. break;
  59174. case LessEqualDepth:
  59175. depthCompare = GPUCompareFunction.LessEqual;
  59176. break;
  59177. case EqualDepth:
  59178. depthCompare = GPUCompareFunction.Equal;
  59179. break;
  59180. case GreaterEqualDepth:
  59181. depthCompare = GPUCompareFunction.GreaterEqual;
  59182. break;
  59183. case GreaterDepth:
  59184. depthCompare = GPUCompareFunction.Greater;
  59185. break;
  59186. case NotEqualDepth:
  59187. depthCompare = GPUCompareFunction.NotEqual;
  59188. break;
  59189. default:
  59190. error( 'WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  59191. }
  59192. }
  59193. return depthCompare;
  59194. }
  59195. }
  59196. /**
  59197. * Reusable descriptor for `GPUDevice.createQuerySet()`.
  59198. *
  59199. * @private
  59200. */
  59201. class GPUQuerySetDescriptor {
  59202. constructor() {
  59203. /**
  59204. * The label of the query set.
  59205. *
  59206. * @type {string}
  59207. */
  59208. this.label = '';
  59209. /**
  59210. * The type of queries managed by the set.
  59211. *
  59212. * @type {string|undefined}
  59213. */
  59214. this.type = undefined;
  59215. /**
  59216. * The number of queries managed by the set.
  59217. *
  59218. * @type {number}
  59219. * @default 0
  59220. */
  59221. this.count = 0;
  59222. }
  59223. /**
  59224. * Resets the descriptor to its default state.
  59225. */
  59226. reset() {
  59227. this.label = '';
  59228. this.type = undefined;
  59229. this.count = 0;
  59230. }
  59231. }
  59232. const _bufferDescriptor$1 = new GPUBufferDescriptor();
  59233. const _commandEncoderDescriptor$1 = new GPUCommandEncoderDescriptor();
  59234. const _querySetDescriptor$1 = new GPUQuerySetDescriptor();
  59235. /**
  59236. * Manages a pool of WebGPU timestamp queries for performance measurement.
  59237. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  59238. *
  59239. * @augments TimestampQueryPool
  59240. */
  59241. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  59242. /**
  59243. * Creates a new WebGPU timestamp query pool.
  59244. *
  59245. * @param {GPUDevice} device - The WebGPU device to create queries on.
  59246. * @param {string} type - The type identifier for this query pool.
  59247. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  59248. */
  59249. constructor( device, type, maxQueries = 2048 ) {
  59250. super( maxQueries );
  59251. this.device = device;
  59252. this.type = type;
  59253. _querySetDescriptor$1.label = `queryset_global_timestamp_${type}`;
  59254. _querySetDescriptor$1.type = 'timestamp';
  59255. _querySetDescriptor$1.count = this.maxQueries;
  59256. this.querySet = this.device.createQuerySet( _querySetDescriptor$1 );
  59257. _querySetDescriptor$1.reset();
  59258. const bufferSize = this.maxQueries * 8;
  59259. _bufferDescriptor$1.label = `buffer_timestamp_resolve_${type}`;
  59260. _bufferDescriptor$1.size = bufferSize;
  59261. _bufferDescriptor$1.usage = GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC;
  59262. this.resolveBuffer = this.device.createBuffer( _bufferDescriptor$1 );
  59263. _bufferDescriptor$1.reset();
  59264. _bufferDescriptor$1.label = `buffer_timestamp_result_${type}`;
  59265. _bufferDescriptor$1.size = bufferSize;
  59266. _bufferDescriptor$1.usage = GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ;
  59267. this.resultBuffer = this.device.createBuffer( _bufferDescriptor$1 );
  59268. _bufferDescriptor$1.reset();
  59269. }
  59270. /**
  59271. * Allocates a pair of queries for a given render context.
  59272. *
  59273. * @param {string} uid - A unique identifier for the render context.
  59274. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  59275. */
  59276. allocateQueriesForContext( uid ) {
  59277. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  59278. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  59279. warnOnce( `WebGPUTimestampQueryPool [${ this.type }]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${ this.type.toUpperCase() } ).` );
  59280. return null;
  59281. }
  59282. const baseOffset = this.currentQueryIndex;
  59283. this.currentQueryIndex += 2;
  59284. this.queryOffsets.set( uid, baseOffset );
  59285. return baseOffset;
  59286. }
  59287. /**
  59288. * Asynchronously resolves all pending queries and returns the total duration.
  59289. * If there's already a pending resolve operation, returns that promise instead.
  59290. *
  59291. * @async
  59292. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  59293. */
  59294. async resolveQueriesAsync() {
  59295. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  59296. return this.lastValue;
  59297. }
  59298. if ( this.pendingResolve ) {
  59299. return this.pendingResolve;
  59300. }
  59301. this.pendingResolve = this._resolveQueries();
  59302. try {
  59303. const result = await this.pendingResolve;
  59304. return result;
  59305. } finally {
  59306. this.pendingResolve = null;
  59307. }
  59308. }
  59309. /**
  59310. * Internal method to resolve queries and calculate total duration.
  59311. *
  59312. * @async
  59313. * @private
  59314. * @returns {Promise<number>} The total duration in milliseconds.
  59315. */
  59316. async _resolveQueries() {
  59317. if ( this.isDisposed ) {
  59318. return this.lastValue;
  59319. }
  59320. try {
  59321. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  59322. return this.lastValue;
  59323. }
  59324. const currentOffsets = new Map( this.queryOffsets );
  59325. const queryCount = this.currentQueryIndex;
  59326. const bytesUsed = queryCount * 8;
  59327. // Reset state before GPU work
  59328. this.currentQueryIndex = 0;
  59329. this.queryOffsets.clear();
  59330. const commandEncoder = this.device.createCommandEncoder( _commandEncoderDescriptor$1 );
  59331. commandEncoder.resolveQuerySet(
  59332. this.querySet,
  59333. 0,
  59334. queryCount,
  59335. this.resolveBuffer,
  59336. 0
  59337. );
  59338. commandEncoder.copyBufferToBuffer(
  59339. this.resolveBuffer,
  59340. 0,
  59341. this.resultBuffer,
  59342. 0,
  59343. bytesUsed
  59344. );
  59345. const commandBuffer = commandEncoder.finish();
  59346. submit( this.device, commandBuffer );
  59347. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  59348. return this.lastValue;
  59349. }
  59350. // Create and track the mapping operation
  59351. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  59352. if ( this.isDisposed ) {
  59353. if ( this.resultBuffer.mapState === 'mapped' ) {
  59354. this.resultBuffer.unmap();
  59355. }
  59356. return this.lastValue;
  59357. }
  59358. //
  59359. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  59360. const framesDuration = {};
  59361. const frames = [];
  59362. for ( const [ uid, baseOffset ] of currentOffsets ) {
  59363. const match = uid.match( /^(.*):f(\d+)$/ );
  59364. const frame = parseInt( match[ 2 ] );
  59365. if ( frames.includes( frame ) === false ) {
  59366. frames.push( frame );
  59367. }
  59368. if ( framesDuration[ frame ] === undefined ) framesDuration[ frame ] = 0;
  59369. const startTime = times[ baseOffset ];
  59370. const endTime = times[ baseOffset + 1 ];
  59371. const duration = Number( endTime - startTime ) / 1e6;
  59372. this.timestamps.set( uid, duration );
  59373. framesDuration[ frame ] += duration;
  59374. }
  59375. // Return the total duration of the last frame
  59376. const totalDuration = framesDuration[ frames[ frames.length - 1 ] ];
  59377. this.resultBuffer.unmap();
  59378. this.lastValue = totalDuration;
  59379. this.frames = frames;
  59380. return totalDuration;
  59381. } catch ( e ) {
  59382. error( 'Error resolving queries:', e );
  59383. if ( this.resultBuffer.mapState === 'mapped' ) {
  59384. this.resultBuffer.unmap();
  59385. }
  59386. return this.lastValue;
  59387. }
  59388. }
  59389. /**
  59390. * Dispose of the query pool.
  59391. *
  59392. * @async
  59393. * @returns {Promise} A Promise that resolves when the dispose has been executed.
  59394. */
  59395. async dispose() {
  59396. if ( this.isDisposed ) {
  59397. return;
  59398. }
  59399. this.isDisposed = true;
  59400. // Wait for pending resolve operation
  59401. if ( this.pendingResolve ) {
  59402. try {
  59403. await this.pendingResolve;
  59404. } catch ( e ) {
  59405. error( 'Error waiting for pending resolve:', e );
  59406. }
  59407. }
  59408. // Ensure buffer is unmapped before destroying
  59409. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  59410. try {
  59411. this.resultBuffer.unmap();
  59412. } catch ( e ) {
  59413. error( 'Error unmapping buffer:', e );
  59414. }
  59415. }
  59416. // Destroy resources
  59417. if ( this.querySet ) {
  59418. this.querySet.destroy();
  59419. this.querySet = null;
  59420. }
  59421. if ( this.resolveBuffer ) {
  59422. this.resolveBuffer.destroy();
  59423. this.resolveBuffer = null;
  59424. }
  59425. if ( this.resultBuffer ) {
  59426. this.resultBuffer.destroy();
  59427. this.resultBuffer = null;
  59428. }
  59429. this.queryOffsets.clear();
  59430. this.pendingResolve = null;
  59431. }
  59432. }
  59433. /**
  59434. * Reusable descriptor for `GPUCommandEncoder.beginComputePass()`.
  59435. *
  59436. * @private
  59437. */
  59438. class GPUComputePassDescriptor {
  59439. constructor() {
  59440. /**
  59441. * The label of the compute pass.
  59442. *
  59443. * @type {string}
  59444. */
  59445. this.label = '';
  59446. /**
  59447. * Defines which timestamp values are written and where.
  59448. *
  59449. * @type {Object|undefined}
  59450. */
  59451. this.timestampWrites = undefined;
  59452. }
  59453. /**
  59454. * Resets the descriptor to its default state.
  59455. */
  59456. reset() {
  59457. this.label = '';
  59458. this.timestampWrites = undefined;
  59459. }
  59460. }
  59461. /**
  59462. * Reusable descriptor for `GPURenderPassDepthStencilAttachment`, the
  59463. * `depthStencilAttachment` field of `GPURenderPassDescriptor`.
  59464. *
  59465. * @private
  59466. */
  59467. class GPURenderPassDepthStencilAttachment {
  59468. constructor() {
  59469. /**
  59470. * The depth/stencil texture view the pass renders into.
  59471. *
  59472. * @type {?GPUTextureView}
  59473. * @default null
  59474. */
  59475. this.view = null;
  59476. /**
  59477. * The load operation applied to the depth aspect at the start of the pass.
  59478. *
  59479. * @type {string|undefined}
  59480. */
  59481. this.depthLoadOp = undefined;
  59482. /**
  59483. * The store operation applied to the depth aspect at the end of the pass.
  59484. *
  59485. * @type {string|undefined}
  59486. */
  59487. this.depthStoreOp = undefined;
  59488. /**
  59489. * The clear value used when `depthLoadOp` is `'clear'`.
  59490. *
  59491. * @type {number|undefined}
  59492. */
  59493. this.depthClearValue = undefined;
  59494. /**
  59495. * Whether the depth aspect is read-only.
  59496. *
  59497. * @type {boolean}
  59498. * @default false
  59499. */
  59500. this.depthReadOnly = false;
  59501. /**
  59502. * The load operation applied to the stencil aspect at the start of the pass.
  59503. *
  59504. * @type {string|undefined}
  59505. */
  59506. this.stencilLoadOp = undefined;
  59507. /**
  59508. * The store operation applied to the stencil aspect at the end of the pass.
  59509. *
  59510. * @type {string|undefined}
  59511. */
  59512. this.stencilStoreOp = undefined;
  59513. /**
  59514. * The clear value used when `stencilLoadOp` is `'clear'`.
  59515. *
  59516. * @type {number}
  59517. * @default 0
  59518. */
  59519. this.stencilClearValue = 0;
  59520. /**
  59521. * Whether the stencil aspect is read-only.
  59522. *
  59523. * @type {boolean}
  59524. * @default false
  59525. */
  59526. this.stencilReadOnly = false;
  59527. }
  59528. /**
  59529. * Resets the descriptor to its default state.
  59530. */
  59531. reset() {
  59532. this.view = null;
  59533. this.depthLoadOp = undefined;
  59534. this.depthStoreOp = undefined;
  59535. this.depthClearValue = undefined;
  59536. this.depthReadOnly = false;
  59537. this.stencilLoadOp = undefined;
  59538. this.stencilStoreOp = undefined;
  59539. this.stencilClearValue = 0;
  59540. this.stencilReadOnly = false;
  59541. }
  59542. }
  59543. /**
  59544. * Reusable descriptor for `GPURenderPassTimestampWrites`, the
  59545. * `timestampWrites` field of `GPURenderPassDescriptor`. The same shape is
  59546. * also accepted as `GPUComputePassTimestampWrites`.
  59547. *
  59548. * @private
  59549. */
  59550. class GPURenderPassTimestampWrites {
  59551. constructor() {
  59552. /**
  59553. * The query set the timestamps are written to.
  59554. *
  59555. * @type {?GPUQuerySet}
  59556. * @default null
  59557. */
  59558. this.querySet = null;
  59559. /**
  59560. * The index in the query set the beginning timestamp is written to.
  59561. *
  59562. * @type {number|undefined}
  59563. */
  59564. this.beginningOfPassWriteIndex = undefined;
  59565. /**
  59566. * The index in the query set the ending timestamp is written to.
  59567. *
  59568. * @type {number|undefined}
  59569. */
  59570. this.endOfPassWriteIndex = undefined;
  59571. }
  59572. /**
  59573. * Resets the descriptor to its default state.
  59574. */
  59575. reset() {
  59576. this.querySet = null;
  59577. this.beginningOfPassWriteIndex = undefined;
  59578. this.endOfPassWriteIndex = undefined;
  59579. }
  59580. }
  59581. // debugger tools
  59582. // import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  59583. const _clearValue = { r: 0, g: 0, b: 0, a: 1 };
  59584. const _bufferDescriptor = new GPUBufferDescriptor();
  59585. const _commandEncoderDescriptor = new GPUCommandEncoderDescriptor();
  59586. const _computePassDescriptor = new GPUComputePassDescriptor();
  59587. const _querySetDescriptor = new GPUQuerySetDescriptor();
  59588. const _shaderModuleDescriptor = new GPUShaderModuleDescriptor();
  59589. const _renderPassTimestampWrites = new GPURenderPassTimestampWrites();
  59590. const _texelCopyTextureInfoSrc = new GPUTexelCopyTextureInfo();
  59591. const _texelCopyTextureInfoDst = new GPUTexelCopyTextureInfo();
  59592. const _viewDescriptor = new GPUTextureViewDescriptor();
  59593. const _extent3D = new GPUExtent3D();
  59594. /**
  59595. * A backend implementation targeting WebGPU.
  59596. *
  59597. * @private
  59598. * @augments Backend
  59599. */
  59600. class WebGPUBackend extends Backend {
  59601. /**
  59602. * WebGPUBackend options.
  59603. *
  59604. * @typedef {Object} WebGPUBackend~Options
  59605. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  59606. * @property {boolean} [reversedDepthBuffer=false] - Whether reversed depth buffer is enabled or not.
  59607. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  59608. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  59609. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  59610. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  59611. * @property {number} [samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0 to overwrite the default.
  59612. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  59613. * @property {boolean} [trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  59614. * @property {string} [powerPreference=undefined] - The power preference.
  59615. * @property {Object} [requiredLimits=undefined] - Specifies the limits that are required by the device request. The request will fail if the adapter cannot provide these limits.
  59616. * @property {GPUDevice} [device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  59617. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  59618. */
  59619. /**
  59620. * Constructs a new WebGPU backend.
  59621. *
  59622. * @param {WebGPUBackend~Options} [parameters] - The configuration parameter.
  59623. */
  59624. constructor( parameters = {} ) {
  59625. super( parameters );
  59626. /**
  59627. * This flag can be used for type testing.
  59628. *
  59629. * @type {boolean}
  59630. * @readonly
  59631. * @default true
  59632. */
  59633. this.isWebGPUBackend = true;
  59634. // some parameters require default values other than "undefined"
  59635. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  59636. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  59637. /**
  59638. * Indicates whether the backend is in WebGPU compatibility mode or not.
  59639. * The backend must be initialized before the property can be evaluated.
  59640. *
  59641. * @type {?boolean}
  59642. * @readonly
  59643. * @default null
  59644. */
  59645. this.compatibilityMode = null;
  59646. /**
  59647. * A reference to the device.
  59648. *
  59649. * @type {?GPUDevice}
  59650. * @default null
  59651. */
  59652. this.device = null;
  59653. /**
  59654. * A reference to the default render pass descriptor.
  59655. *
  59656. * @type {?Object}
  59657. * @default null
  59658. */
  59659. this.defaultRenderPassdescriptor = null;
  59660. /**
  59661. * A reference to a backend module holding common utility functions.
  59662. *
  59663. * @type {WebGPUUtils}
  59664. */
  59665. this.utils = new WebGPUUtils( this );
  59666. /**
  59667. * A reference to a backend module holding shader attribute-related
  59668. * utility functions.
  59669. *
  59670. * @type {WebGPUAttributeUtils}
  59671. */
  59672. this.attributeUtils = new WebGPUAttributeUtils( this );
  59673. /**
  59674. * A reference to a backend module holding shader binding-related
  59675. * utility functions.
  59676. *
  59677. * @type {WebGPUBindingUtils}
  59678. */
  59679. this.bindingUtils = new WebGPUBindingUtils( this );
  59680. /**
  59681. * A reference to a backend module holding device capability related
  59682. * utility functions.
  59683. *
  59684. * @type {WebGPUCapabilities}
  59685. */
  59686. this.capabilities = new WebGPUCapabilities( this );
  59687. /**
  59688. * A reference to a backend module holding shader pipeline-related
  59689. * utility functions.
  59690. *
  59691. * @type {WebGPUPipelineUtils}
  59692. */
  59693. this.pipelineUtils = new WebGPUPipelineUtils( this );
  59694. /**
  59695. * A reference to a backend module holding shader texture-related
  59696. * utility functions.
  59697. *
  59698. * @type {WebGPUTextureUtils}
  59699. */
  59700. this.textureUtils = new WebGPUTextureUtils( this );
  59701. /**
  59702. * A map that manages the resolve buffers for occlusion queries.
  59703. *
  59704. * @type {Map<number,GPUBuffer>}
  59705. */
  59706. this.occludedResolveCache = new Map();
  59707. // compatibility checks
  59708. const compatibilityTextureCompare = typeof navigator === 'undefined' ? true : /Android/.test( navigator.userAgent ) === false;
  59709. /**
  59710. * A map of compatibility checks.
  59711. *
  59712. * @type {Object}
  59713. */
  59714. this._compatibility = {
  59715. [ Compatibility.TEXTURE_COMPARE ]: compatibilityTextureCompare
  59716. };
  59717. }
  59718. /**
  59719. * Initializes the backend so it is ready for usage.
  59720. *
  59721. * @async
  59722. * @param {Renderer} renderer - The renderer.
  59723. * @return {Promise} A Promise that resolves when the backend has been initialized.
  59724. */
  59725. async init( renderer ) {
  59726. await super.init( renderer );
  59727. //
  59728. const parameters = this.parameters;
  59729. // create the device if it is not passed with parameters
  59730. let device;
  59731. if ( parameters.device === undefined ) {
  59732. const adapterOptions = {
  59733. powerPreference: parameters.powerPreference,
  59734. featureLevel: 'compatibility',
  59735. xrCompatible: renderer.xr.enabled
  59736. };
  59737. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  59738. if ( adapter === null ) {
  59739. throw new Error( 'THREE.WebGPUBackend: Unable to create WebGPU adapter.' );
  59740. }
  59741. // feature support
  59742. const features = Object.values( GPUFeatureName );
  59743. const supportedFeatures = [];
  59744. for ( const name of features ) {
  59745. if ( adapter.features.has( name ) ) {
  59746. supportedFeatures.push( name );
  59747. }
  59748. }
  59749. const deviceDescriptor = {
  59750. requiredFeatures: supportedFeatures,
  59751. requiredLimits: parameters.requiredLimits
  59752. };
  59753. device = await adapter.requestDevice( deviceDescriptor );
  59754. } else {
  59755. device = parameters.device;
  59756. }
  59757. this.compatibilityMode = ! device.features.has( 'core-features-and-limits' );
  59758. if ( this.compatibilityMode ) {
  59759. renderer._samples = 0;
  59760. }
  59761. device.lost.then( ( info ) => {
  59762. if ( info.reason === 'destroyed' ) return;
  59763. const deviceLossInfo = {
  59764. api: 'WebGPU',
  59765. message: info.message || 'Unknown reason',
  59766. reason: info.reason || null,
  59767. originalEvent: info
  59768. };
  59769. renderer.onDeviceLost( deviceLossInfo );
  59770. } );
  59771. device.onuncapturederror = ( event ) => {
  59772. const gpuError = event.error;
  59773. const type = gpuError && gpuError.constructor ? gpuError.constructor.name : 'GPUError';
  59774. const message = ( gpuError && gpuError.message ) || 'Unknown uncaptured GPU error';
  59775. renderer.onError( {
  59776. api: 'WebGPU',
  59777. type,
  59778. message,
  59779. originalEvent: event
  59780. } );
  59781. };
  59782. this.device = device;
  59783. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  59784. this.updateSize();
  59785. }
  59786. /**
  59787. * Registers external GPU textures from `XRGPUBinding` for use in rendering.
  59788. *
  59789. * @param {RenderTarget} renderTarget - The render target to register the textures for.
  59790. * @param {GPUTexture} colorTexture - The shared XR color GPUTexture.
  59791. * @param {?Array<Object>} [viewDescriptors=null] - Optional view descriptors, one per XR view.
  59792. */
  59793. setXRRenderTargetTextures( renderTarget, colorTexture, viewDescriptors = null ) {
  59794. this.set( renderTarget.texture, {
  59795. texture: colorTexture,
  59796. format: colorTexture.format,
  59797. externalTexture: true,
  59798. xrViewDescriptors: viewDescriptors,
  59799. initialized: true
  59800. } );
  59801. }
  59802. /**
  59803. * A reference to the context.
  59804. *
  59805. * @type {?GPUCanvasContext}
  59806. * @default null
  59807. */
  59808. get context() {
  59809. const canvasTarget = this.renderer.getCanvasTarget();
  59810. const canvasData = this.get( canvasTarget );
  59811. let context = canvasData.context;
  59812. if ( context === undefined ) {
  59813. const parameters = this.parameters;
  59814. if ( canvasTarget.isDefaultCanvasTarget === true && parameters.context !== undefined ) {
  59815. context = parameters.context;
  59816. } else {
  59817. context = canvasTarget.domElement.getContext( 'webgpu' );
  59818. }
  59819. // OffscreenCanvas does not have setAttribute, see #22811
  59820. if ( 'setAttribute' in canvasTarget.domElement ) canvasTarget.domElement.setAttribute( 'data-engine', `three.js r${ REVISION } webgpu` );
  59821. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  59822. const toneMappingMode = parameters.outputType === HalfFloatType ? 'extended' : 'standard';
  59823. context.configure( {
  59824. device: this.device,
  59825. format: this.utils.getPreferredCanvasFormat(),
  59826. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  59827. alphaMode: alphaMode,
  59828. toneMapping: {
  59829. mode: toneMappingMode
  59830. }
  59831. } );
  59832. canvasData.context = context;
  59833. }
  59834. return context;
  59835. }
  59836. /**
  59837. * The coordinate system of the backend.
  59838. *
  59839. * @type {number}
  59840. * @readonly
  59841. */
  59842. get coordinateSystem() {
  59843. return WebGPUCoordinateSystem;
  59844. }
  59845. /**
  59846. * Whether the backend supports query timestamps or not.
  59847. *
  59848. * @type {boolean}
  59849. * @readonly
  59850. */
  59851. get hasTimestamp() {
  59852. return true;
  59853. }
  59854. /**
  59855. * This method performs a readback operation by moving buffer data from
  59856. * a storage buffer attribute from the GPU to the CPU. ReadbackBuffer can
  59857. * be used to retain and reuse handles to the intermediate buffers and prevent
  59858. * new allocation.
  59859. *
  59860. * @async
  59861. * @param {BufferAttribute} attribute - The storage buffer attribute to read frm.
  59862. * @param {number} count - The offset from which to start reading the
  59863. * @param {number} offset - The storage buffer attribute.
  59864. * @param {ReadbackBuffer|ArrayBuffer} target - The storage buffer attribute.
  59865. * @return {Promise<ArrayBuffer|ReadbackBuffer>} A promise that resolves with the buffer data when the data are ready.
  59866. */
  59867. async getArrayBufferAsync( attribute, target = null, offset = 0, count = -1 ) {
  59868. return await this.attributeUtils.getArrayBufferAsync( attribute, target, offset, count );
  59869. }
  59870. /**
  59871. * Returns the backend's rendering context.
  59872. *
  59873. * @return {GPUCanvasContext} The rendering context.
  59874. */
  59875. getContext() {
  59876. return this.context;
  59877. }
  59878. /**
  59879. * Returns the default render pass descriptor.
  59880. *
  59881. * In WebGPU, the default framebuffer must be configured
  59882. * like custom framebuffers so the backend needs a render
  59883. * pass descriptor even when rendering directly to screen.
  59884. *
  59885. * @private
  59886. * @return {GPURenderPassDescriptor} The render pass descriptor.
  59887. */
  59888. _getDefaultRenderPassDescriptor() {
  59889. const renderer = this.renderer;
  59890. const canvasTarget = renderer.getCanvasTarget();
  59891. const canvasData = this.get( canvasTarget );
  59892. const samples = renderer.currentSamples;
  59893. let descriptor = canvasData.descriptor;
  59894. if ( descriptor === undefined || canvasData.samples !== samples ) {
  59895. descriptor = new GPURenderPassDescriptor();
  59896. descriptor.colorAttachments.push( new GPURenderPassColorAttachment() );
  59897. if ( renderer.depth === true || renderer.stencil === true ) {
  59898. const depthStencilAttachment = new GPURenderPassDepthStencilAttachment();
  59899. depthStencilAttachment.view = this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView();
  59900. descriptor.depthStencilAttachment = depthStencilAttachment;
  59901. }
  59902. const colorAttachment = descriptor.colorAttachments[ 0 ];
  59903. if ( samples > 0 ) {
  59904. colorAttachment.view = this.textureUtils.getColorBuffer().createView();
  59905. } else {
  59906. colorAttachment.resolveTarget = undefined;
  59907. }
  59908. canvasData.descriptor = descriptor;
  59909. canvasData.samples = samples;
  59910. }
  59911. const colorAttachment = descriptor.colorAttachments[ 0 ];
  59912. if ( samples > 0 ) {
  59913. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  59914. } else {
  59915. colorAttachment.view = this.context.getCurrentTexture().createView();
  59916. }
  59917. return descriptor;
  59918. }
  59919. /**
  59920. * Returns whether the render target is a render target array with depth 2D array texture.
  59921. *
  59922. * @param {RenderContext} renderContext - The render context.
  59923. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  59924. *
  59925. * @private
  59926. */
  59927. _isRenderCameraDepthArray( renderContext ) {
  59928. const camera = renderContext.camera;
  59929. return renderContext.depthTexture && renderContext.depthTexture.isArrayTexture === true && camera !== null && camera.isArrayCamera === true;
  59930. }
  59931. /**
  59932. * Returns whether the current render context references external textures.
  59933. *
  59934. * External textures can change every frame, so their descriptors must not be cached.
  59935. *
  59936. * @private
  59937. * @param {RenderContext} renderContext - The render context.
  59938. * @return {boolean} Whether the render context uses external textures.
  59939. */
  59940. _hasExternalTexture( renderContext ) {
  59941. const textures = renderContext.textures;
  59942. if ( textures === null ) return false;
  59943. for ( let i = 0; i < textures.length; i ++ ) {
  59944. if ( this.get( textures[ i ] ).externalTexture === true ) return true;
  59945. }
  59946. return false;
  59947. }
  59948. /**
  59949. * Creates attachment views for an external texture render target.
  59950. *
  59951. * @private
  59952. * @param {RenderContext} renderContext - The render context.
  59953. * @param {Object} textureData - The backend data for the texture.
  59954. * @return {Array<Object>} The attachment view descriptors.
  59955. */
  59956. _createExternalTextureViews( renderContext, textureData ) {
  59957. const textureViews = [];
  59958. const camera = renderContext.camera;
  59959. if ( textureData.xrViewDescriptors && camera !== null && camera.isArrayCamera === true ) {
  59960. for ( let i = 0; i < textureData.xrViewDescriptors.length; i ++ ) {
  59961. textureViews.push( {
  59962. view: textureData.texture.createView( textureData.xrViewDescriptors[ i ] ),
  59963. resolveTarget: undefined,
  59964. depthSlice: undefined
  59965. } );
  59966. }
  59967. } else {
  59968. textureViews.push( {
  59969. view: textureData.texture.createView( {
  59970. dimension: GPUTextureViewDimension.TwoD,
  59971. baseArrayLayer: renderContext.activeCubeFace,
  59972. arrayLayerCount: 1
  59973. } ),
  59974. resolveTarget: undefined,
  59975. depthSlice: undefined
  59976. } );
  59977. }
  59978. return textureViews;
  59979. }
  59980. /**
  59981. * Returns the render pass descriptor for the given render context.
  59982. *
  59983. * @private
  59984. * @param {RenderContext} renderContext - The render context.
  59985. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  59986. * @return {Object} The render pass descriptor.
  59987. */
  59988. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  59989. const renderTarget = renderContext.renderTarget;
  59990. const renderTargetData = this.get( renderTarget );
  59991. const hasExternalTexture = this._hasExternalTexture( renderContext );
  59992. let descriptors = renderTargetData.descriptors;
  59993. if ( descriptors === undefined ||
  59994. renderTargetData.width !== renderTarget.width ||
  59995. renderTargetData.height !== renderTarget.height ||
  59996. renderTargetData.samples !== renderTarget.samples ||
  59997. hasExternalTexture
  59998. ) {
  59999. descriptors = {};
  60000. renderTargetData.descriptors = descriptors;
  60001. }
  60002. const cacheKey = renderContext.getCacheKey();
  60003. let descriptorBase = descriptors[ cacheKey ];
  60004. if ( descriptorBase === undefined || hasExternalTexture ) {
  60005. const textures = renderContext.textures;
  60006. const textureViews = [];
  60007. let sliceIndex;
  60008. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( renderContext );
  60009. for ( let i = 0; i < textures.length; i ++ ) {
  60010. const textureData = this.get( textures[ i ] );
  60011. if ( textureData.externalTexture === true ) {
  60012. textureViews.push( ...this._createExternalTextureViews( renderContext, textureData ) );
  60013. continue;
  60014. }
  60015. _viewDescriptor.label = `colorAttachment_${ i }`;
  60016. _viewDescriptor.baseMipLevel = renderContext.activeMipmapLevel;
  60017. _viewDescriptor.mipLevelCount = 1;
  60018. _viewDescriptor.baseArrayLayer = renderContext.activeCubeFace;
  60019. _viewDescriptor.arrayLayerCount = 1;
  60020. _viewDescriptor.dimension = GPUTextureViewDimension.TwoD;
  60021. if ( renderTarget.isRenderTarget3D ) {
  60022. sliceIndex = renderContext.activeCubeFace;
  60023. _viewDescriptor.baseArrayLayer = 0;
  60024. _viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  60025. } else if ( renderTarget.isRenderTarget && textures[ i ].image.depth > 1 ) {
  60026. if ( isRenderCameraDepthArray === true ) {
  60027. const cameras = renderContext.camera.cameras;
  60028. for ( let layer = 0; layer < cameras.length; layer ++ ) {
  60029. _viewDescriptor.baseArrayLayer = layer;
  60030. _viewDescriptor.arrayLayerCount = 1;
  60031. _viewDescriptor.dimension = GPUTextureViewDimension.TwoD;
  60032. const textureView = textureData.texture.createView( _viewDescriptor );
  60033. textureViews.push( {
  60034. view: textureView,
  60035. resolveTarget: undefined,
  60036. depthSlice: undefined
  60037. } );
  60038. }
  60039. } else {
  60040. _viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  60041. }
  60042. }
  60043. if ( isRenderCameraDepthArray !== true ) {
  60044. const textureView = textureData.texture.createView( _viewDescriptor );
  60045. let view, resolveTarget;
  60046. if ( textureData.msaaTexture !== undefined ) {
  60047. view = textureData.msaaTexture.createView();
  60048. resolveTarget = renderTarget.resolveColorBuffer === true ? textureView : undefined;
  60049. } else {
  60050. view = textureView;
  60051. resolveTarget = undefined;
  60052. }
  60053. textureViews.push( {
  60054. view,
  60055. resolveTarget,
  60056. depthSlice: sliceIndex
  60057. } );
  60058. }
  60059. _viewDescriptor.reset();
  60060. }
  60061. const colorAttachments = [];
  60062. for ( let i = 0; i < textureViews.length; i ++ ) {
  60063. const viewInfo = textureViews[ i ];
  60064. const attachment = new GPURenderPassColorAttachment();
  60065. attachment.view = viewInfo.view;
  60066. attachment.depthSlice = viewInfo.depthSlice;
  60067. attachment.resolveTarget = viewInfo.resolveTarget;
  60068. colorAttachments.push( attachment );
  60069. }
  60070. descriptorBase = {
  60071. textureViews,
  60072. colorAttachments,
  60073. descriptor: new GPURenderPassDescriptor()
  60074. };
  60075. if ( renderContext.depth ) {
  60076. const depthTextureData = this.get( renderContext.depthTexture );
  60077. if ( renderContext.depthTexture.isArrayTexture || renderContext.depthTexture.isCubeTexture ) {
  60078. _viewDescriptor.dimension = GPUTextureViewDimension.TwoD;
  60079. _viewDescriptor.arrayLayerCount = 1;
  60080. _viewDescriptor.baseArrayLayer = renderContext.activeCubeFace;
  60081. }
  60082. const depthStencilAttachment = new GPURenderPassDepthStencilAttachment();
  60083. depthStencilAttachment.view = depthTextureData.texture.createView( _viewDescriptor );
  60084. descriptorBase.depthStencilAttachment = depthStencilAttachment;
  60085. _viewDescriptor.reset();
  60086. }
  60087. descriptors[ cacheKey ] = descriptorBase;
  60088. renderTargetData.width = renderTarget.width;
  60089. renderTargetData.height = renderTarget.height;
  60090. renderTargetData.samples = renderTarget.samples;
  60091. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  60092. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  60093. }
  60094. const descriptor = descriptorBase.descriptor;
  60095. descriptor.reset();
  60096. // Apply dynamic properties to cached attachments
  60097. for ( let i = 0; i < descriptorBase.colorAttachments.length; i ++ ) {
  60098. const attachment = descriptorBase.colorAttachments[ i ];
  60099. let clearValue = { r: 0, g: 0, b: 0, a: 1 };
  60100. if ( i === 0 && colorAttachmentsConfig.clearValue ) {
  60101. clearValue = colorAttachmentsConfig.clearValue;
  60102. }
  60103. attachment.loadOp = colorAttachmentsConfig.loadOp || GPULoadOp.Load;
  60104. attachment.storeOp = colorAttachmentsConfig.storeOp || GPUStoreOp.Store;
  60105. attachment.clearValue = clearValue;
  60106. descriptor.colorAttachments.push( attachment );
  60107. }
  60108. if ( descriptorBase.depthStencilAttachment ) {
  60109. descriptor.depthStencilAttachment = descriptorBase.depthStencilAttachment;
  60110. }
  60111. return descriptor;
  60112. }
  60113. /**
  60114. * This method is executed at the beginning of a render call and prepares
  60115. * the WebGPU state for upcoming render calls
  60116. *
  60117. * @param {RenderContext} renderContext - The render context.
  60118. */
  60119. beginRender( renderContext ) {
  60120. const renderContextData = this.get( renderContext );
  60121. //
  60122. const device = this.device;
  60123. const occlusionQueryCount = renderContext.occlusionQueryCount;
  60124. let occlusionQuerySet;
  60125. if ( occlusionQueryCount > 0 ) {
  60126. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  60127. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  60128. // Get a reference to the array of objects with queries. The renderContextData property
  60129. // can be changed by another render pass before the buffer.mapAsyc() completes.
  60130. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  60131. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  60132. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  60133. //
  60134. _querySetDescriptor.label = `occlusionQuerySet_${ renderContext.id }`;
  60135. _querySetDescriptor.type = 'occlusion';
  60136. _querySetDescriptor.count = occlusionQueryCount;
  60137. occlusionQuerySet = device.createQuerySet( _querySetDescriptor );
  60138. _querySetDescriptor.reset();
  60139. renderContextData.occlusionQuerySet = occlusionQuerySet;
  60140. renderContextData.occlusionQueryIndex = 0;
  60141. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  60142. renderContextData.lastOcclusionObject = null;
  60143. } else if ( renderContextData.lastOcclusionObject !== undefined ) {
  60144. // invalidate if there is a stale query
  60145. renderContextData.lastOcclusionObject = undefined;
  60146. renderContextData.occlusionQuerySet.destroy();
  60147. renderContextData.occlusionQuerySet = undefined;
  60148. }
  60149. let descriptor;
  60150. if ( renderContext.textures === null ) {
  60151. descriptor = this._getDefaultRenderPassDescriptor();
  60152. } else {
  60153. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  60154. }
  60155. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ), descriptor );
  60156. descriptor.occlusionQuerySet = occlusionQuerySet;
  60157. const depthStencilAttachment = descriptor.depthStencilAttachment;
  60158. const renderTarget = renderContext.renderTarget;
  60159. if ( renderContext.textures !== null ) {
  60160. const colorAttachments = descriptor.colorAttachments;
  60161. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  60162. const colorAttachment = colorAttachments[ i ];
  60163. if ( renderContext.clearColor ) {
  60164. if ( i === 0 ) {
  60165. colorAttachment.clearValue = renderContext.clearColorValue;
  60166. } else {
  60167. _clearValue.r = 0;
  60168. _clearValue.g = 0;
  60169. _clearValue.b = 0;
  60170. _clearValue.a = 1;
  60171. colorAttachment.clearValue = _clearValue;
  60172. }
  60173. colorAttachment.loadOp = GPULoadOp.Clear;
  60174. } else {
  60175. colorAttachment.loadOp = GPULoadOp.Load;
  60176. }
  60177. if ( renderContext.sampleCount > 1 && renderTarget?.storeMultisampledColorBuffer === false ) {
  60178. colorAttachment.storeOp = GPUStoreOp.Discard;
  60179. } else {
  60180. colorAttachment.storeOp = GPUStoreOp.Store;
  60181. }
  60182. }
  60183. } else {
  60184. const colorAttachment = descriptor.colorAttachments[ 0 ];
  60185. if ( renderContext.clearColor ) {
  60186. colorAttachment.clearValue = renderContext.clearColorValue;
  60187. colorAttachment.loadOp = GPULoadOp.Clear;
  60188. } else {
  60189. colorAttachment.loadOp = GPULoadOp.Load;
  60190. }
  60191. colorAttachment.storeOp = GPUStoreOp.Store;
  60192. }
  60193. //
  60194. if ( renderContext.depth ) {
  60195. if ( renderContext.clearDepth ) {
  60196. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  60197. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  60198. } else {
  60199. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  60200. }
  60201. if ( renderContext.sampleCount > 1 && renderTarget?.storeMultisampledDepthBuffer === false ) {
  60202. depthStencilAttachment.depthStoreOp = GPUStoreOp.Discard;
  60203. } else {
  60204. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  60205. }
  60206. }
  60207. if ( renderContext.stencil ) {
  60208. if ( renderContext.clearStencil ) {
  60209. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  60210. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  60211. } else {
  60212. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  60213. }
  60214. if ( renderContext.sampleCount > 1 && renderTarget?.storeMultisampledStencilBuffer === false ) {
  60215. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Discard;
  60216. } else {
  60217. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  60218. }
  60219. }
  60220. //
  60221. _commandEncoderDescriptor.label = 'renderContext_' + renderContext.id;
  60222. const encoder = device.createCommandEncoder( _commandEncoderDescriptor );
  60223. _commandEncoderDescriptor.reset();
  60224. // Layered render targets: prepare bundle encoders for each camera in the array camera.
  60225. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  60226. const cameras = renderContext.camera.cameras;
  60227. if ( ! renderContextData.layerDescriptors || renderContextData.layerDescriptors.length !== cameras.length ) {
  60228. this._createArrayCameraLayerDescriptors( renderContext, renderContextData, descriptor, cameras );
  60229. } else {
  60230. this._updateArrayCameraLayerDescriptors( renderContext, renderContextData, cameras );
  60231. }
  60232. // Create bundle encoders for each layer
  60233. renderContextData.bundleEncoders = [];
  60234. renderContextData.bundleSets = [];
  60235. // Create separate bundle encoders for each camera in the array
  60236. for ( let i = 0; i < cameras.length; i ++ ) {
  60237. const bundleEncoder = this.pipelineUtils.createBundleEncoder(
  60238. renderContext,
  60239. 'renderBundleArrayCamera_' + i
  60240. );
  60241. // Initialize state tracking for this bundle
  60242. const bundleSets = {
  60243. attributes: {},
  60244. bindingGroups: [],
  60245. pipeline: null,
  60246. index: null
  60247. };
  60248. renderContextData.bundleEncoders.push( bundleEncoder );
  60249. renderContextData.bundleSets.push( bundleSets );
  60250. }
  60251. // We'll complete the bundles in finishRender
  60252. renderContextData.currentPass = null;
  60253. } else {
  60254. const currentPass = encoder.beginRenderPass( descriptor );
  60255. renderContextData.currentPass = currentPass;
  60256. if ( renderContext.viewport ) {
  60257. this.updateViewport( renderContext );
  60258. }
  60259. if ( renderContext.scissor ) {
  60260. this.updateScissor( renderContext );
  60261. }
  60262. }
  60263. //
  60264. renderContextData.descriptor = descriptor;
  60265. renderContextData.encoder = encoder;
  60266. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  60267. renderContextData.renderBundles = [];
  60268. }
  60269. /**
  60270. * Creates render pass descriptors for each camera in an array camera.
  60271. *
  60272. * @param {RenderContext} renderContext - The render context.
  60273. * @param {Object} renderContextData - The render context data.
  60274. * @param {Object} descriptor - The render pass descriptor.
  60275. * @param {ArrayCamera} cameras - The array camera.
  60276. *
  60277. * @private
  60278. */
  60279. _createArrayCameraLayerDescriptors( renderContext, renderContextData, descriptor, cameras ) {
  60280. const depthStencilAttachment = descriptor.depthStencilAttachment;
  60281. renderContextData.layerDescriptors = [];
  60282. const depthTextureData = this.get( renderContext.depthTexture );
  60283. if ( ! depthTextureData.viewCache ) {
  60284. depthTextureData.viewCache = [];
  60285. }
  60286. for ( let i = 0; i < cameras.length; i ++ ) {
  60287. const sourceAttachment = descriptor.colorAttachments[ 0 ];
  60288. const layerColorAttachment = new GPURenderPassColorAttachment();
  60289. layerColorAttachment.view = descriptor.colorAttachments[ i ].view;
  60290. layerColorAttachment.depthSlice = sourceAttachment.depthSlice;
  60291. layerColorAttachment.resolveTarget = sourceAttachment.resolveTarget;
  60292. layerColorAttachment.loadOp = sourceAttachment.loadOp;
  60293. layerColorAttachment.storeOp = sourceAttachment.storeOp;
  60294. layerColorAttachment.clearValue = sourceAttachment.clearValue;
  60295. const layerDescriptor = new GPURenderPassDescriptor();
  60296. layerDescriptor.label = descriptor.label;
  60297. layerDescriptor.occlusionQuerySet = descriptor.occlusionQuerySet;
  60298. layerDescriptor.timestampWrites = descriptor.timestampWrites;
  60299. layerDescriptor.colorAttachments.push( layerColorAttachment );
  60300. if ( descriptor.depthStencilAttachment ) {
  60301. const layerIndex = i;
  60302. if ( ! depthTextureData.viewCache[ layerIndex ] ) {
  60303. _viewDescriptor.dimension = GPUTextureViewDimension.TwoD;
  60304. _viewDescriptor.baseArrayLayer = i;
  60305. _viewDescriptor.arrayLayerCount = 1;
  60306. depthTextureData.viewCache[ layerIndex ] = depthTextureData.texture.createView( _viewDescriptor );
  60307. _viewDescriptor.reset();
  60308. }
  60309. const layerDepthStencilAttachment = new GPURenderPassDepthStencilAttachment();
  60310. layerDepthStencilAttachment.view = depthTextureData.viewCache[ layerIndex ];
  60311. layerDepthStencilAttachment.depthLoadOp = depthStencilAttachment.depthLoadOp || GPULoadOp.Clear;
  60312. layerDepthStencilAttachment.depthStoreOp = depthStencilAttachment.depthStoreOp || GPUStoreOp.Store;
  60313. layerDepthStencilAttachment.depthClearValue = depthStencilAttachment.depthClearValue || 1.0;
  60314. if ( renderContext.stencil ) {
  60315. layerDepthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  60316. layerDepthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  60317. layerDepthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  60318. }
  60319. layerDescriptor.depthStencilAttachment = layerDepthStencilAttachment;
  60320. } else {
  60321. const layerDepthStencilAttachment = new GPURenderPassDepthStencilAttachment();
  60322. layerDepthStencilAttachment.view = depthStencilAttachment.view;
  60323. layerDepthStencilAttachment.depthLoadOp = depthStencilAttachment.depthLoadOp;
  60324. layerDepthStencilAttachment.depthStoreOp = depthStencilAttachment.depthStoreOp;
  60325. layerDepthStencilAttachment.depthClearValue = depthStencilAttachment.depthClearValue;
  60326. layerDepthStencilAttachment.depthReadOnly = depthStencilAttachment.depthReadOnly;
  60327. layerDepthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  60328. layerDepthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  60329. layerDepthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  60330. layerDepthStencilAttachment.stencilReadOnly = depthStencilAttachment.stencilReadOnly;
  60331. layerDescriptor.depthStencilAttachment = layerDepthStencilAttachment;
  60332. }
  60333. renderContextData.layerDescriptors.push( layerDescriptor );
  60334. }
  60335. }
  60336. /**
  60337. * Updates render pass descriptors for each camera in an array camera.
  60338. *
  60339. * @param {RenderContext} renderContext - The render context.
  60340. * @param {Object} renderContextData - The render context data.
  60341. * @param {ArrayCamera} cameras - The array camera.
  60342. *
  60343. */
  60344. _updateArrayCameraLayerDescriptors( renderContext, renderContextData, cameras ) {
  60345. for ( let i = 0; i < cameras.length; i ++ ) {
  60346. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  60347. if ( layerDescriptor.depthStencilAttachment ) {
  60348. const depthAttachment = layerDescriptor.depthStencilAttachment;
  60349. if ( renderContext.depth ) {
  60350. if ( renderContext.clearDepth ) {
  60351. depthAttachment.depthClearValue = renderContext.clearDepthValue;
  60352. depthAttachment.depthLoadOp = GPULoadOp.Clear;
  60353. } else {
  60354. depthAttachment.depthLoadOp = GPULoadOp.Load;
  60355. }
  60356. }
  60357. if ( renderContext.stencil ) {
  60358. if ( renderContext.clearStencil ) {
  60359. depthAttachment.stencilClearValue = renderContext.clearStencilValue;
  60360. depthAttachment.stencilLoadOp = GPULoadOp.Clear;
  60361. } else {
  60362. depthAttachment.stencilLoadOp = GPULoadOp.Load;
  60363. }
  60364. }
  60365. }
  60366. }
  60367. }
  60368. /**
  60369. * This method is executed at the end of a render call and finalizes work
  60370. * after draw calls.
  60371. *
  60372. * @param {RenderContext} renderContext - The render context.
  60373. */
  60374. finishRender( renderContext ) {
  60375. const renderContextData = this.get( renderContext );
  60376. const occlusionQueryCount = renderContext.occlusionQueryCount;
  60377. if ( renderContextData.renderBundles.length > 0 ) {
  60378. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  60379. }
  60380. const lastOcclusionObject = renderContextData.lastOcclusionObject;
  60381. if ( lastOcclusionObject && lastOcclusionObject.occlusionTest === true ) {
  60382. renderContextData.currentPass.endOcclusionQuery();
  60383. }
  60384. // Layered render targets: execute the bundle for each layer.
  60385. const encoder = renderContextData.encoder;
  60386. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  60387. const bundles = [];
  60388. for ( let i = 0; i < renderContextData.bundleEncoders.length; i ++ ) {
  60389. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  60390. bundles.push( bundleEncoder.finish() );
  60391. }
  60392. for ( let i = 0; i < renderContextData.layerDescriptors.length; i ++ ) {
  60393. if ( i < bundles.length ) {
  60394. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  60395. const renderPass = encoder.beginRenderPass( layerDescriptor );
  60396. if ( renderContext.viewport ) {
  60397. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  60398. renderPass.setViewport( x, y, width, height, minDepth, maxDepth );
  60399. }
  60400. if ( renderContext.scissor ) {
  60401. const { x, y, width, height } = renderContext.scissorValue;
  60402. renderPass.setScissorRect( x, y, width, height );
  60403. }
  60404. renderPass.executeBundles( [ bundles[ i ] ] );
  60405. renderPass.end();
  60406. }
  60407. }
  60408. } else if ( renderContextData.currentPass ) {
  60409. renderContextData.currentPass.end();
  60410. }
  60411. if ( occlusionQueryCount > 0 ) {
  60412. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  60413. //
  60414. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  60415. if ( queryResolveBuffer === undefined ) {
  60416. _bufferDescriptor.size = bufferSize;
  60417. _bufferDescriptor.usage = GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC;
  60418. queryResolveBuffer = this.device.createBuffer( _bufferDescriptor );
  60419. _bufferDescriptor.reset();
  60420. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  60421. }
  60422. //
  60423. _bufferDescriptor.size = bufferSize;
  60424. _bufferDescriptor.usage = GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ;
  60425. const readBuffer = this.device.createBuffer( _bufferDescriptor );
  60426. _bufferDescriptor.reset();
  60427. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  60428. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  60429. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  60430. renderContextData.occlusionQueryBuffer = readBuffer;
  60431. //
  60432. this.resolveOccludedAsync( renderContext );
  60433. }
  60434. submit( this.device, renderContextData.encoder.finish() );
  60435. //
  60436. if ( renderContext.textures !== null ) {
  60437. const textures = renderContext.textures;
  60438. for ( let i = 0; i < textures.length; i ++ ) {
  60439. const texture = textures[ i ];
  60440. if ( texture.generateMipmaps === true ) {
  60441. this.textureUtils.generateMipmaps( texture );
  60442. }
  60443. }
  60444. }
  60445. }
  60446. /**
  60447. * Returns `true` if the given 3D object is fully occluded by other
  60448. * 3D objects in the scene.
  60449. *
  60450. * @param {RenderContext} renderContext - The render context.
  60451. * @param {Object3D} object - The 3D object to test.
  60452. * @return {boolean} Whether the 3D object is fully occluded or not.
  60453. */
  60454. isOccluded( renderContext, object ) {
  60455. const renderContextData = this.get( renderContext );
  60456. return renderContextData.occluded && renderContextData.occluded.has( object );
  60457. }
  60458. /**
  60459. * This method processes the result of occlusion queries and writes it
  60460. * into render context data.
  60461. *
  60462. * @async
  60463. * @param {RenderContext} renderContext - The render context.
  60464. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  60465. */
  60466. async resolveOccludedAsync( renderContext ) {
  60467. const renderContextData = this.get( renderContext );
  60468. // handle occlusion query results
  60469. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  60470. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  60471. const occluded = new WeakSet();
  60472. renderContextData.currentOcclusionQueryObjects = null;
  60473. renderContextData.currentOcclusionQueryBuffer = null;
  60474. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  60475. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  60476. const results = new BigUint64Array( buffer );
  60477. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  60478. const object = currentOcclusionQueryObjects[ i ];
  60479. if ( object !== undefined && results[ i ] === BigInt( 0 ) ) {
  60480. occluded.add( object );
  60481. }
  60482. }
  60483. currentOcclusionQueryBuffer.destroy();
  60484. renderContextData.occluded = occluded;
  60485. }
  60486. }
  60487. /**
  60488. * Updates the viewport with the values from the given render context.
  60489. *
  60490. * @param {RenderContext} renderContext - The render context.
  60491. */
  60492. updateViewport( renderContext ) {
  60493. const { currentPass } = this.get( renderContext );
  60494. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  60495. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  60496. }
  60497. /**
  60498. * Updates the scissor with the values from the given render context.
  60499. *
  60500. * @param {RenderContext} renderContext - The render context.
  60501. */
  60502. updateScissor( renderContext ) {
  60503. const { currentPass } = this.get( renderContext );
  60504. const { x, y, width, height } = renderContext.scissorValue;
  60505. currentPass.setScissorRect( x, y, width, height );
  60506. }
  60507. /**
  60508. * Returns the clear color and alpha into a single
  60509. * color object.
  60510. *
  60511. * @return {Color4} The clear color.
  60512. */
  60513. getClearColor() {
  60514. const clearColor = super.getClearColor();
  60515. // only premultiply alpha when alphaMode is "premultiplied"
  60516. if ( this.renderer.alpha === true ) {
  60517. clearColor.r *= clearColor.a;
  60518. clearColor.g *= clearColor.a;
  60519. clearColor.b *= clearColor.a;
  60520. }
  60521. return clearColor;
  60522. }
  60523. /**
  60524. * Performs a clear operation.
  60525. *
  60526. * @param {boolean} color - Whether the color buffer should be cleared or not.
  60527. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  60528. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  60529. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  60530. */
  60531. clear( color, depth, stencil, renderTargetContext = null ) {
  60532. const device = this.device;
  60533. const renderer = this.renderer;
  60534. let colorAttachments = [];
  60535. let depthStencilAttachment;
  60536. let supportsDepth;
  60537. let supportsStencil;
  60538. if ( color ) {
  60539. const clearColor = this.getClearColor();
  60540. _clearValue.r = clearColor.r;
  60541. _clearValue.g = clearColor.g;
  60542. _clearValue.b = clearColor.b;
  60543. _clearValue.a = clearColor.a;
  60544. }
  60545. if ( renderTargetContext === null ) {
  60546. supportsDepth = renderer.depth;
  60547. supportsStencil = renderer.stencil;
  60548. const descriptor = this._getDefaultRenderPassDescriptor();
  60549. if ( color ) {
  60550. colorAttachments = descriptor.colorAttachments;
  60551. const colorAttachment = colorAttachments[ 0 ];
  60552. colorAttachment.clearValue = _clearValue;
  60553. colorAttachment.loadOp = GPULoadOp.Clear;
  60554. colorAttachment.storeOp = GPUStoreOp.Store;
  60555. }
  60556. if ( supportsDepth || supportsStencil ) {
  60557. depthStencilAttachment = descriptor.depthStencilAttachment;
  60558. }
  60559. } else {
  60560. supportsDepth = renderTargetContext.depth;
  60561. supportsStencil = renderTargetContext.stencil;
  60562. const clearConfig = {
  60563. loadOp: color ? GPULoadOp.Clear : GPULoadOp.Load,
  60564. clearValue: color ? _clearValue : undefined
  60565. };
  60566. if ( supportsDepth ) {
  60567. clearConfig.depthLoadOp = depth ? GPULoadOp.Clear : GPULoadOp.Load;
  60568. clearConfig.depthClearValue = depth ? renderer.getClearDepth() : undefined;
  60569. clearConfig.depthStoreOp = GPUStoreOp.Store;
  60570. }
  60571. if ( supportsStencil ) {
  60572. clearConfig.stencilLoadOp = stencil ? GPULoadOp.Clear : GPULoadOp.Load;
  60573. clearConfig.stencilClearValue = stencil ? renderer.getClearStencil() : undefined;
  60574. clearConfig.stencilStoreOp = GPUStoreOp.Store;
  60575. }
  60576. const descriptor = this._getRenderPassDescriptor( renderTargetContext, clearConfig );
  60577. colorAttachments = descriptor.colorAttachments;
  60578. depthStencilAttachment = descriptor.depthStencilAttachment;
  60579. }
  60580. if ( supportsDepth && depthStencilAttachment ) {
  60581. if ( depth ) {
  60582. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  60583. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  60584. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  60585. } else {
  60586. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  60587. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  60588. }
  60589. }
  60590. //
  60591. if ( supportsStencil && depthStencilAttachment ) {
  60592. if ( stencil ) {
  60593. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  60594. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  60595. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  60596. } else {
  60597. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  60598. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  60599. }
  60600. }
  60601. //
  60602. _commandEncoderDescriptor.label = 'clear';
  60603. const encoder = device.createCommandEncoder( _commandEncoderDescriptor );
  60604. _commandEncoderDescriptor.reset();
  60605. const currentPass = encoder.beginRenderPass( {
  60606. colorAttachments,
  60607. depthStencilAttachment
  60608. } );
  60609. currentPass.end();
  60610. submit( device, encoder.finish() );
  60611. }
  60612. // compute
  60613. /**
  60614. * This method is executed at the beginning of a compute call and
  60615. * prepares the state for upcoming compute tasks.
  60616. *
  60617. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  60618. */
  60619. beginCompute( computeGroup ) {
  60620. const groupGPU = this.get( computeGroup );
  60621. //
  60622. const label = 'computeGroup_' + computeGroup.id;
  60623. _computePassDescriptor.label = label;
  60624. _commandEncoderDescriptor.label = label;
  60625. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ), _computePassDescriptor );
  60626. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( _commandEncoderDescriptor );
  60627. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( _computePassDescriptor );
  60628. groupGPU.currentPipeline = null;
  60629. _commandEncoderDescriptor.reset();
  60630. _computePassDescriptor.reset();
  60631. }
  60632. /**
  60633. * Executes a compute command for the given compute node.
  60634. *
  60635. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  60636. * @param {Node} computeNode - The compute node.
  60637. * @param {Array<BindGroup>} bindings - The bindings.
  60638. * @param {ComputePipeline} pipeline - The compute pipeline.
  60639. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  60640. * - A single number representing count, or
  60641. * - An array [x, y, z] representing dispatch size, or
  60642. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  60643. */
  60644. compute( computeGroup, computeNode, bindings, pipeline, dispatchSize = null ) {
  60645. const computeNodeData = this.get( computeNode );
  60646. const groupGPU = this.get( computeGroup );
  60647. const { passEncoderGPU } = groupGPU;
  60648. // pipeline
  60649. const pipelineGPU = this.get( pipeline ).pipeline;
  60650. if ( groupGPU.currentPipeline !== pipelineGPU ) {
  60651. passEncoderGPU.setPipeline( pipelineGPU );
  60652. groupGPU.currentPipeline = pipelineGPU;
  60653. }
  60654. // bind groups
  60655. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  60656. const bindGroup = bindings[ i ];
  60657. const bindingsData = this.get( bindGroup );
  60658. passEncoderGPU.setBindGroup( i, bindingsData.group );
  60659. }
  60660. if ( dispatchSize === null ) {
  60661. dispatchSize = computeNode.dispatchSize || computeNode.count;
  60662. }
  60663. // When the dispatchSize is set with a StorageBuffer from the GPU.
  60664. if ( dispatchSize && dispatchSize.isIndirectStorageBufferAttribute ) {
  60665. const dispatchBuffer = this.get( dispatchSize ).buffer;
  60666. passEncoderGPU.dispatchWorkgroupsIndirect( dispatchBuffer, 0 );
  60667. return;
  60668. }
  60669. if ( typeof dispatchSize === 'number' ) {
  60670. // If a single number is given, we calculate the dispatch size based on the workgroup size
  60671. const count = dispatchSize;
  60672. if ( computeNodeData.dispatchSize === undefined || computeNodeData.count !== count ) {
  60673. // cache dispatch size to avoid recalculating it every time
  60674. computeNodeData.dispatchSize = [ 0, 1, 1 ];
  60675. computeNodeData.count = count;
  60676. const workgroupSize = computeNode.workgroupSize;
  60677. let size = workgroupSize[ 0 ];
  60678. for ( let i = 1; i < workgroupSize.length; i ++ )
  60679. size *= workgroupSize[ i ];
  60680. const dispatchCount = Math.ceil( count / size );
  60681. //
  60682. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  60683. dispatchSize = [ dispatchCount, 1, 1 ];
  60684. if ( dispatchCount > maxComputeWorkgroupsPerDimension ) {
  60685. dispatchSize[ 0 ] = Math.min( dispatchCount, maxComputeWorkgroupsPerDimension );
  60686. dispatchSize[ 1 ] = Math.ceil( dispatchCount / maxComputeWorkgroupsPerDimension );
  60687. }
  60688. computeNodeData.dispatchSize = dispatchSize;
  60689. }
  60690. dispatchSize = computeNodeData.dispatchSize;
  60691. }
  60692. //
  60693. passEncoderGPU.dispatchWorkgroups(
  60694. dispatchSize[ 0 ],
  60695. dispatchSize[ 1 ] || 1,
  60696. dispatchSize[ 2 ] || 1
  60697. );
  60698. }
  60699. /**
  60700. * This method is executed at the end of a compute call and
  60701. * finalizes work after compute tasks.
  60702. *
  60703. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  60704. */
  60705. finishCompute( computeGroup ) {
  60706. const groupData = this.get( computeGroup );
  60707. groupData.passEncoderGPU.end();
  60708. submit( this.device, groupData.cmdEncoderGPU.finish() );
  60709. }
  60710. /**
  60711. * Internal draw function that performs the draw with the given pass encoder.
  60712. *
  60713. * @private
  60714. * @param {RenderObject} renderObject - The render object.
  60715. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  60716. * @param {Object} renderContextData - The render context data object, holding current pass state and occlusion query tracking.
  60717. * @param {GPURenderPipeline} pipelineGPU - The GPU render pipeline.
  60718. * @param {Array<BindGroup>} bindings - The bind groups.
  60719. * @param {Array<BufferAttribute>} vertexBuffers - The vertex buffers.
  60720. * @param {{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} drawParams - The draw parameters.
  60721. * @param {GPURenderPassEncoder|GPURenderBundleEncoder} passEncoderGPU - The GPU pass encoder used for recording draw commands.
  60722. * @param {Object} currentSets - Tracking object for currently set pipeline, attributes, bind groups, and index state.
  60723. */
  60724. _draw( renderObject, info, renderContextData, pipelineGPU, bindings, vertexBuffers, drawParams, passEncoderGPU, currentSets ) {
  60725. const { object, material, context } = renderObject;
  60726. const index = renderObject.getIndex();
  60727. const hasIndex = ( index !== null );
  60728. // pipeline
  60729. if ( currentSets.pipeline !== pipelineGPU ) {
  60730. passEncoderGPU.setPipeline( pipelineGPU );
  60731. currentSets.pipeline = pipelineGPU;
  60732. }
  60733. // bind groups
  60734. const currentBindingGroups = currentSets.bindingGroups;
  60735. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  60736. const bindGroup = bindings[ i ];
  60737. if ( currentBindingGroups[ i ] !== bindGroup.id ) {
  60738. const bindingsData = this.get( bindGroup );
  60739. passEncoderGPU.setBindGroup( i, bindingsData.group );
  60740. currentBindingGroups[ i ] = bindGroup.id;
  60741. }
  60742. }
  60743. // attributes
  60744. // index
  60745. if ( hasIndex === true ) {
  60746. if ( currentSets.index !== index ) {
  60747. const buffer = this.get( index ).buffer;
  60748. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  60749. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  60750. currentSets.index = index;
  60751. }
  60752. }
  60753. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  60754. const vertexBuffer = vertexBuffers[ i ];
  60755. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  60756. const buffer = this.get( vertexBuffer ).buffer;
  60757. passEncoderGPU.setVertexBuffer( i, buffer );
  60758. currentSets.attributes[ i ] = vertexBuffer;
  60759. }
  60760. }
  60761. // stencil
  60762. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  60763. passEncoderGPU.setStencilReference( material.stencilRef );
  60764. renderContextData.currentStencilRef = material.stencilRef;
  60765. }
  60766. if ( object.isBatchedMesh === true ) {
  60767. const starts = object._multiDrawStarts;
  60768. const counts = object._multiDrawCounts;
  60769. const drawCount = object._multiDrawCount;
  60770. let bytesPerElement = ( hasIndex === true ) ? index.array.BYTES_PER_ELEMENT : 1;
  60771. if ( material.wireframe ) {
  60772. bytesPerElement = object.geometry.attributes.position.count > 65535 ? 4 : 2;
  60773. }
  60774. for ( let i = 0; i < drawCount; i ++ ) {
  60775. if ( hasIndex === true ) {
  60776. passEncoderGPU.drawIndexed( counts[ i ], 1, starts[ i ] / bytesPerElement, 0, i );
  60777. } else {
  60778. passEncoderGPU.draw( counts[ i ], 1, starts[ i ], i );
  60779. }
  60780. info.update( object, counts[ i ], 1 );
  60781. }
  60782. } else if ( hasIndex === true ) {
  60783. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  60784. const indirect = renderObject.getIndirect();
  60785. if ( indirect !== null ) {
  60786. const buffer = this.get( indirect ).buffer;
  60787. const indirectOffset = renderObject.getIndirectOffset();
  60788. const indirectOffsets = Array.isArray( indirectOffset ) ? indirectOffset : [ indirectOffset ];
  60789. for ( let i = 0; i < indirectOffsets.length; i ++ ) {
  60790. passEncoderGPU.drawIndexedIndirect( buffer, indirectOffsets[ i ] );
  60791. }
  60792. } else {
  60793. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  60794. }
  60795. info.update( object, indexCount, instanceCount );
  60796. } else {
  60797. const { vertexCount, instanceCount, firstVertex } = drawParams;
  60798. const indirect = renderObject.getIndirect();
  60799. if ( indirect !== null ) {
  60800. const buffer = this.get( indirect ).buffer;
  60801. const indirectOffset = renderObject.getIndirectOffset();
  60802. const indirectOffsets = Array.isArray( indirectOffset ) ? indirectOffset : [ indirectOffset ];
  60803. for ( let i = 0; i < indirectOffsets.length; i ++ ) {
  60804. passEncoderGPU.drawIndirect( buffer, indirectOffsets[ i ] );
  60805. }
  60806. } else {
  60807. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  60808. }
  60809. info.update( object, vertexCount, instanceCount );
  60810. }
  60811. }
  60812. // render object
  60813. /**
  60814. * Executes a draw command for the given render object.
  60815. *
  60816. * @param {RenderObject} renderObject - The render object to draw.
  60817. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  60818. */
  60819. draw( renderObject, info ) {
  60820. const { object, context, pipeline } = renderObject;
  60821. const renderContextData = this.get( context );
  60822. const pipelineData = this.get( pipeline );
  60823. const pipelineGPU = pipelineData.pipeline;
  60824. // Skip if pipeline has error
  60825. if ( pipelineData.error === true ) return;
  60826. const drawParams = renderObject.getDrawParameters();
  60827. if ( drawParams === null ) return;
  60828. const bindings = renderObject.getBindings();
  60829. // vertex buffers
  60830. const vertexBuffers = renderObject.getVertexBuffers();
  60831. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  60832. const cameraData = this.get( renderObject.camera );
  60833. const cameras = renderObject.camera.cameras;
  60834. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  60835. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  60836. const bindingsData = this.get( cameraIndex );
  60837. const indexesGPU = [];
  60838. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  60839. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  60840. data[ 0 ] = i;
  60841. const { layoutGPU } = bindingsData.layout;
  60842. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, layoutGPU );
  60843. indexesGPU.push( bindGroupIndex );
  60844. }
  60845. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  60846. }
  60847. const pixelRatio = this.renderer.getPixelRatio();
  60848. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  60849. const subCamera = cameras[ i ];
  60850. if ( object.layers.test( subCamera.layers ) ) {
  60851. const vp = subCamera.viewport;
  60852. let pass = renderContextData.currentPass;
  60853. let sets = renderContextData.currentSets;
  60854. const isBundleEncoder = renderContextData.bundleEncoders !== undefined;
  60855. if ( isBundleEncoder ) {
  60856. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  60857. const bundleSets = renderContextData.bundleSets[ i ];
  60858. pass = bundleEncoder;
  60859. sets = bundleSets;
  60860. }
  60861. // GPURenderBundleEncoder does not support setViewport, only GPURenderPassEncoder does
  60862. if ( vp && ! isBundleEncoder ) {
  60863. pass.setViewport(
  60864. Math.floor( vp.x * pixelRatio ),
  60865. Math.floor( vp.y * pixelRatio ),
  60866. Math.floor( vp.width * pixelRatio ),
  60867. Math.floor( vp.height * pixelRatio ),
  60868. context.viewportValue.minDepth,
  60869. context.viewportValue.maxDepth
  60870. );
  60871. }
  60872. // Set camera index binding for this layer
  60873. if ( cameraIndex && cameraData.indexesGPU ) {
  60874. const indexPos = bindings.indexOf( cameraIndex );
  60875. pass.setBindGroup( indexPos, cameraData.indexesGPU[ i ] );
  60876. sets.bindingGroups[ indexPos ] = cameraIndex.id;
  60877. }
  60878. this._draw( renderObject, info, renderContextData, pipelineGPU, bindings, vertexBuffers, drawParams, pass, sets );
  60879. }
  60880. }
  60881. } else {
  60882. // Regular single camera rendering
  60883. if ( renderContextData.currentPass ) {
  60884. // Handle occlusion queries
  60885. if ( renderContextData.occlusionQuerySet !== undefined ) {
  60886. const lastObject = renderContextData.lastOcclusionObject;
  60887. if ( lastObject !== object ) {
  60888. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  60889. renderContextData.currentPass.endOcclusionQuery();
  60890. renderContextData.occlusionQueryIndex ++;
  60891. }
  60892. if ( object.occlusionTest === true ) {
  60893. renderContextData.currentPass.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  60894. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  60895. }
  60896. renderContextData.lastOcclusionObject = object;
  60897. }
  60898. }
  60899. this._draw( renderObject, info, renderContextData, pipelineGPU, bindings, vertexBuffers, drawParams, renderContextData.currentPass, renderContextData.currentSets );
  60900. }
  60901. }
  60902. }
  60903. // cache key
  60904. /**
  60905. * Returns `true` if the render pipeline requires an update.
  60906. *
  60907. * @param {RenderObject} renderObject - The render object.
  60908. * @return {boolean} Whether the render pipeline requires an update or not.
  60909. */
  60910. needsRenderUpdate( renderObject ) {
  60911. const data = this.get( renderObject );
  60912. const { object, material } = renderObject;
  60913. const utils = this.utils;
  60914. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  60915. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  60916. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  60917. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  60918. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  60919. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinantAffine() < 0 );
  60920. let needsUpdate = false;
  60921. if ( data.material !== material || data.materialVersion !== material.version ||
  60922. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  60923. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  60924. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  60925. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  60926. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  60927. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  60928. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  60929. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  60930. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  60931. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  60932. data.primitiveTopology !== primitiveTopology ||
  60933. data.frontFaceCW !== frontFaceCW ||
  60934. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  60935. ) {
  60936. data.material = material; data.materialVersion = material.version;
  60937. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  60938. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  60939. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  60940. data.colorWrite = material.colorWrite;
  60941. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  60942. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  60943. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  60944. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  60945. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  60946. data.sampleCount = sampleCount;
  60947. data.colorSpace = colorSpace;
  60948. data.colorFormat = colorFormat;
  60949. data.depthStencilFormat = depthStencilFormat;
  60950. data.primitiveTopology = primitiveTopology;
  60951. data.frontFaceCW = frontFaceCW;
  60952. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  60953. needsUpdate = true;
  60954. }
  60955. return needsUpdate;
  60956. }
  60957. /**
  60958. * Returns a cache key that is used to identify render pipelines.
  60959. *
  60960. * @param {RenderObject} renderObject - The render object.
  60961. * @return {string} The cache key.
  60962. */
  60963. getRenderCacheKey( renderObject ) {
  60964. const { object, material } = renderObject;
  60965. const utils = this.utils;
  60966. const renderContext = renderObject.context;
  60967. // meshes with negative scale have a different frontFace render pipeline
  60968. // descriptor value so the following must be honored in the cache key
  60969. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinantAffine() < 0 );
  60970. return [
  60971. material.transparent, material.blending, material.premultipliedAlpha,
  60972. material.blendSrc, material.blendDst, material.blendEquation,
  60973. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  60974. material.colorWrite,
  60975. material.depthWrite, material.depthTest, material.depthFunc,
  60976. material.stencilWrite, material.stencilFunc,
  60977. material.stencilFail, material.stencilZFail, material.stencilZPass,
  60978. material.stencilFuncMask, material.stencilWriteMask,
  60979. material.side,
  60980. frontFaceCW,
  60981. utils.getSampleCountRenderContext( renderContext ),
  60982. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  60983. utils.getPrimitiveTopology( object, material ),
  60984. renderObject.getGeometryCacheKey(),
  60985. renderObject.clippingContextCacheKey
  60986. ].join();
  60987. }
  60988. // textures
  60989. /**
  60990. * Updates a GPU sampler for the given texture.
  60991. *
  60992. * @param {Sampler} binding - The sampler binding to update.
  60993. * @return {string} The current sampler key.
  60994. */
  60995. updateSampler( binding ) {
  60996. return this.textureUtils.updateSampler( binding );
  60997. }
  60998. /**
  60999. * Frees the GPU sampler for the given sampler binding.
  61000. *
  61001. * @param {Sampler} binding - The sampler binding to free.
  61002. */
  61003. destroySampler( binding ) {
  61004. this.textureUtils.destroySampler( binding );
  61005. }
  61006. /**
  61007. * Creates a default texture for the given texture that can be used
  61008. * as a placeholder until the actual texture is ready for usage.
  61009. *
  61010. * @param {Texture} texture - The texture to create a default texture for.
  61011. * @return {boolean} Whether the sampler has been updated or not.
  61012. */
  61013. createDefaultTexture( texture ) {
  61014. return this.textureUtils.createDefaultTexture( texture );
  61015. }
  61016. /**
  61017. * Defines a texture on the GPU for the given texture object.
  61018. *
  61019. * @param {Texture} texture - The texture.
  61020. * @param {Object} [options={}] - Optional configuration parameter.
  61021. */
  61022. createTexture( texture, options ) {
  61023. this.textureUtils.createTexture( texture, options );
  61024. }
  61025. /**
  61026. * Uploads the updated texture data to the GPU.
  61027. *
  61028. * @param {Texture} texture - The texture.
  61029. * @param {Object} [options={}] - Optional configuration parameter.
  61030. */
  61031. updateTexture( texture, options ) {
  61032. this.textureUtils.updateTexture( texture, options );
  61033. }
  61034. /**
  61035. * Generates mipmaps for the given texture.
  61036. *
  61037. * @param {Texture} texture - The texture.
  61038. */
  61039. generateMipmaps( texture ) {
  61040. this.textureUtils.generateMipmaps( texture );
  61041. }
  61042. /**
  61043. * Destroys the GPU data for the given texture object.
  61044. *
  61045. * @param {Texture} texture - The texture.
  61046. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  61047. */
  61048. destroyTexture( texture, isDefaultTexture = false ) {
  61049. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  61050. }
  61051. /**
  61052. * Returns texture data as a typed array.
  61053. *
  61054. * @async
  61055. * @param {Texture} texture - The texture to copy.
  61056. * @param {number} x - The x coordinate of the copy origin.
  61057. * @param {number} y - The y coordinate of the copy origin.
  61058. * @param {number} width - The width of the copy.
  61059. * @param {number} height - The height of the copy.
  61060. * @param {number} faceIndex - The face index.
  61061. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  61062. */
  61063. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  61064. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  61065. }
  61066. /**
  61067. * Inits a time stamp query for the given render context.
  61068. *
  61069. * @param {string} type - The type of the timestamp query (e.g. 'render', 'compute').
  61070. * @param {number} uid - Unique id for the context (e.g. render context id).
  61071. * @param {Object} descriptor - The query descriptor.
  61072. */
  61073. initTimestampQuery( type, uid, descriptor ) {
  61074. if ( ! this.trackTimestamp ) return;
  61075. if ( ! this.timestampQueryPool[ type ] ) {
  61076. // TODO: Variable maxQueries?
  61077. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  61078. }
  61079. const timestampQueryPool = this.timestampQueryPool[ type ];
  61080. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  61081. _renderPassTimestampWrites.querySet = timestampQueryPool.querySet;
  61082. _renderPassTimestampWrites.beginningOfPassWriteIndex = baseOffset;
  61083. _renderPassTimestampWrites.endOfPassWriteIndex = baseOffset + 1;
  61084. descriptor.timestampWrites = _renderPassTimestampWrites;
  61085. }
  61086. // node builder
  61087. /**
  61088. * Returns a node builder for the given render object.
  61089. *
  61090. * @param {RenderObject} object - The render object.
  61091. * @param {Renderer} renderer - The renderer.
  61092. * @return {WGSLNodeBuilder} The node builder.
  61093. */
  61094. createNodeBuilder( object, renderer ) {
  61095. return new WGSLNodeBuilder( object, renderer );
  61096. }
  61097. // program
  61098. /**
  61099. * Creates a shader program from the given programmable stage.
  61100. *
  61101. * @param {ProgrammableStage} program - The programmable stage.
  61102. */
  61103. createProgram( program ) {
  61104. const programGPU = this.get( program );
  61105. _shaderModuleDescriptor.label = program.stage + ( program.name !== '' ? `_${ program.name }` : '' );
  61106. _shaderModuleDescriptor.code = program.code;
  61107. programGPU.module = {
  61108. module: this.device.createShaderModule( _shaderModuleDescriptor ),
  61109. entryPoint: 'main'
  61110. };
  61111. _shaderModuleDescriptor.reset();
  61112. }
  61113. /**
  61114. * Destroys the shader program of the given programmable stage.
  61115. *
  61116. * @param {ProgrammableStage} program - The programmable stage.
  61117. */
  61118. destroyProgram( program ) {
  61119. this.delete( program );
  61120. }
  61121. // pipelines
  61122. /**
  61123. * Creates a render pipeline for the given render object.
  61124. *
  61125. * @param {RenderObject} renderObject - The render object.
  61126. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  61127. */
  61128. createRenderPipeline( renderObject, promises ) {
  61129. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  61130. }
  61131. /**
  61132. * Creates a compute pipeline for the given compute node.
  61133. *
  61134. * @param {ComputePipeline} computePipeline - The compute pipeline.
  61135. * @param {Array<BindGroup>} bindings - The bindings.
  61136. */
  61137. createComputePipeline( computePipeline, bindings ) {
  61138. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  61139. }
  61140. /**
  61141. * Prepares the state for encoding render bundles.
  61142. *
  61143. * @param {RenderContext} renderContext - The render context.
  61144. */
  61145. beginBundle( renderContext ) {
  61146. const renderContextData = this.get( renderContext );
  61147. renderContextData._currentPass = renderContextData.currentPass;
  61148. renderContextData._currentSets = renderContextData.currentSets;
  61149. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  61150. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  61151. }
  61152. /**
  61153. * After processing render bundles this method finalizes related work.
  61154. *
  61155. * @param {RenderContext} renderContext - The render context.
  61156. * @param {RenderBundle} bundle - The render bundle.
  61157. */
  61158. finishBundle( renderContext, bundle ) {
  61159. const renderContextData = this.get( renderContext );
  61160. const bundleEncoder = renderContextData.currentPass;
  61161. const bundleGPU = bundleEncoder.finish();
  61162. this.get( bundle ).bundleGPU = bundleGPU;
  61163. // restore render pass state
  61164. renderContextData.currentSets = renderContextData._currentSets;
  61165. renderContextData.currentPass = renderContextData._currentPass;
  61166. renderContextData._currentPass = null;
  61167. renderContextData._currentSets = null;
  61168. }
  61169. /**
  61170. * Adds a render bundle to the render context data.
  61171. *
  61172. * @param {RenderContext} renderContext - The render context.
  61173. * @param {RenderBundle} bundle - The render bundle to add.
  61174. */
  61175. addBundle( renderContext, bundle ) {
  61176. const renderContextData = this.get( renderContext );
  61177. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  61178. }
  61179. // bindings
  61180. /**
  61181. * Creates a uniform buffer.
  61182. *
  61183. * @param {Buffer} uniformBuffer - The uniform buffer.
  61184. */
  61185. createUniformBuffer( uniformBuffer ) {
  61186. const uniformBufferData = this.get( uniformBuffer );
  61187. if ( uniformBufferData.buffer === undefined ) {
  61188. const byteLength = uniformBuffer.byteLength;
  61189. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  61190. const visibilities = [];
  61191. if ( uniformBuffer.visibility & GPUShaderStage.VERTEX ) {
  61192. visibilities.push( 'vertex' );
  61193. }
  61194. if ( uniformBuffer.visibility & GPUShaderStage.FRAGMENT ) {
  61195. visibilities.push( 'fragment' );
  61196. }
  61197. if ( uniformBuffer.visibility & GPUShaderStage.COMPUTE ) {
  61198. visibilities.push( 'compute' );
  61199. }
  61200. const bufferVisibility = `(${visibilities.join( ',' )})`;
  61201. _bufferDescriptor.label = `bindingBuffer${uniformBuffer.id}_${uniformBuffer.name}_${bufferVisibility}`;
  61202. _bufferDescriptor.size = byteLength;
  61203. _bufferDescriptor.usage = usage;
  61204. const bufferGPU = this.device.createBuffer( _bufferDescriptor );
  61205. _bufferDescriptor.reset();
  61206. uniformBufferData.buffer = bufferGPU;
  61207. }
  61208. }
  61209. /**
  61210. * Destroys the GPU data for the given uniform buffer.
  61211. *
  61212. * @param {Buffer} uniformBuffer - The uniform buffer.
  61213. */
  61214. destroyUniformBuffer( uniformBuffer ) {
  61215. const uniformBufferData = this.get( uniformBuffer );
  61216. uniformBufferData.buffer.destroy();
  61217. this.delete( uniformBuffer );
  61218. }
  61219. /**
  61220. * Creates bindings from the given bind group definition.
  61221. *
  61222. * @param {BindGroup} bindGroup - The bind group.
  61223. * @param {Array<BindGroup>} bindings - Array of bind groups.
  61224. * @param {number} cacheIndex - The cache index.
  61225. * @param {number} version - The version.
  61226. */
  61227. createBindings( bindGroup, bindings, cacheIndex, version ) {
  61228. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  61229. }
  61230. /**
  61231. * Updates the given bind group definition.
  61232. *
  61233. * @param {BindGroup} bindGroup - The bind group.
  61234. * @param {Array<BindGroup>} bindings - Array of bind groups.
  61235. * @param {number} cacheIndex - The cache index.
  61236. * @param {number} version - The version.
  61237. */
  61238. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  61239. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  61240. }
  61241. /**
  61242. * Updates a buffer binding.
  61243. *
  61244. * @param {Buffer} binding - The buffer binding to update.
  61245. */
  61246. updateBinding( binding ) {
  61247. this.bindingUtils.updateBinding( binding );
  61248. }
  61249. /**
  61250. * Delete data associated with the current bind group.
  61251. *
  61252. * @param {BindGroup} bindGroup - The bind group.
  61253. */
  61254. deleteBindGroupData( bindGroup ) {
  61255. this.bindingUtils.deleteBindGroupData( bindGroup );
  61256. }
  61257. // attributes
  61258. /**
  61259. * Creates the buffer of an indexed shader attribute.
  61260. *
  61261. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  61262. */
  61263. createIndexAttribute( attribute ) {
  61264. let usage = GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST;
  61265. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  61266. usage |= GPUBufferUsage.STORAGE;
  61267. }
  61268. this.attributeUtils.createAttribute( attribute, usage );
  61269. }
  61270. /**
  61271. * Creates the GPU buffer of a shader attribute.
  61272. *
  61273. * @param {BufferAttribute} attribute - The buffer attribute.
  61274. */
  61275. createAttribute( attribute ) {
  61276. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  61277. }
  61278. /**
  61279. * Creates the GPU buffer of a storage attribute.
  61280. *
  61281. * @param {BufferAttribute} attribute - The buffer attribute.
  61282. */
  61283. createStorageAttribute( attribute ) {
  61284. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  61285. }
  61286. /**
  61287. * Creates the GPU buffer of an indirect storage attribute.
  61288. *
  61289. * @param {BufferAttribute} attribute - The buffer attribute.
  61290. */
  61291. createIndirectStorageAttribute( attribute ) {
  61292. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  61293. }
  61294. /**
  61295. * Updates the GPU buffer of a shader attribute.
  61296. *
  61297. * @param {BufferAttribute} attribute - The buffer attribute to update.
  61298. */
  61299. updateAttribute( attribute ) {
  61300. this.attributeUtils.updateAttribute( attribute );
  61301. }
  61302. /**
  61303. * Destroys the GPU buffer of a shader attribute.
  61304. *
  61305. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  61306. */
  61307. destroyAttribute( attribute ) {
  61308. this.attributeUtils.destroyAttribute( attribute );
  61309. }
  61310. // canvas
  61311. /**
  61312. * Triggers an update of the default render pass descriptor.
  61313. */
  61314. updateSize() {
  61315. this.delete( this.renderer.getCanvasTarget() );
  61316. }
  61317. // utils public
  61318. /**
  61319. * Checks if the given feature is supported by the backend.
  61320. *
  61321. * @param {string} name - The feature's name.
  61322. * @return {boolean} Whether the feature is supported or not.
  61323. */
  61324. hasFeature( name ) {
  61325. if ( GPUFeatureMap[ name ] !== undefined ) name = GPUFeatureMap[ name ];
  61326. return this.device.features.has( name );
  61327. }
  61328. /**
  61329. * Copies data of the given source texture to the given destination texture.
  61330. *
  61331. * @param {Texture} srcTexture - The source texture.
  61332. * @param {Texture} dstTexture - The destination texture.
  61333. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  61334. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  61335. * @param {number} [srcLevel=0] - The mipmap level to copy.
  61336. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  61337. */
  61338. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  61339. let dstX = 0;
  61340. let dstY = 0;
  61341. let dstZ = 0;
  61342. let srcX = 0;
  61343. let srcY = 0;
  61344. let srcZ = 0;
  61345. let srcWidth = srcTexture.image.width;
  61346. let srcHeight = srcTexture.image.height;
  61347. let srcDepth = 1;
  61348. if ( srcRegion !== null ) {
  61349. if ( srcRegion.isBox3 === true ) {
  61350. srcX = srcRegion.min.x;
  61351. srcY = srcRegion.min.y;
  61352. srcZ = srcRegion.min.z;
  61353. srcWidth = srcRegion.max.x - srcRegion.min.x;
  61354. srcHeight = srcRegion.max.y - srcRegion.min.y;
  61355. srcDepth = srcRegion.max.z - srcRegion.min.z;
  61356. } else {
  61357. // Assume it's a Box2
  61358. srcX = srcRegion.min.x;
  61359. srcY = srcRegion.min.y;
  61360. srcWidth = srcRegion.max.x - srcRegion.min.x;
  61361. srcHeight = srcRegion.max.y - srcRegion.min.y;
  61362. srcDepth = 1;
  61363. }
  61364. }
  61365. if ( dstPosition !== null ) {
  61366. dstX = dstPosition.x;
  61367. dstY = dstPosition.y;
  61368. dstZ = dstPosition.z || 0;
  61369. }
  61370. _commandEncoderDescriptor.label = 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id;
  61371. const encoder = this.device.createCommandEncoder( _commandEncoderDescriptor );
  61372. _commandEncoderDescriptor.reset();
  61373. const sourceGPU = this.get( srcTexture ).texture;
  61374. const destinationGPU = this.get( dstTexture ).texture;
  61375. _texelCopyTextureInfoSrc.texture = sourceGPU;
  61376. _texelCopyTextureInfoSrc.mipLevel = srcLevel;
  61377. _texelCopyTextureInfoSrc.origin.x = srcX;
  61378. _texelCopyTextureInfoSrc.origin.y = srcY;
  61379. _texelCopyTextureInfoSrc.origin.z = srcZ;
  61380. _texelCopyTextureInfoDst.texture = destinationGPU;
  61381. _texelCopyTextureInfoDst.mipLevel = dstLevel;
  61382. _texelCopyTextureInfoDst.origin.x = dstX;
  61383. _texelCopyTextureInfoDst.origin.y = dstY;
  61384. _texelCopyTextureInfoDst.origin.z = dstZ;
  61385. _extent3D.width = srcWidth;
  61386. _extent3D.height = srcHeight;
  61387. _extent3D.depthOrArrayLayers = srcDepth;
  61388. encoder.copyTextureToTexture(
  61389. _texelCopyTextureInfoSrc,
  61390. _texelCopyTextureInfoDst,
  61391. _extent3D
  61392. );
  61393. _texelCopyTextureInfoSrc.reset();
  61394. _texelCopyTextureInfoDst.reset();
  61395. _extent3D.reset();
  61396. submit( this.device, encoder.finish() );
  61397. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  61398. this.textureUtils.generateMipmaps( dstTexture );
  61399. }
  61400. }
  61401. /**
  61402. * Copies the current bound framebuffer to the given texture.
  61403. *
  61404. * @param {Texture} texture - The destination texture.
  61405. * @param {RenderContext} renderContext - The render context.
  61406. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  61407. */
  61408. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  61409. const renderContextData = this.get( renderContext );
  61410. let sourceGPU = null;
  61411. if ( renderContext.renderTarget ) {
  61412. if ( texture.isDepthTexture ) {
  61413. sourceGPU = this.get( renderContext.depthTexture ).texture;
  61414. } else {
  61415. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  61416. }
  61417. } else {
  61418. if ( texture.isDepthTexture ) {
  61419. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  61420. } else {
  61421. sourceGPU = this.context.getCurrentTexture();
  61422. }
  61423. }
  61424. const destinationGPU = this.get( texture ).texture;
  61425. if ( sourceGPU.format !== destinationGPU.format ) {
  61426. error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  61427. return;
  61428. }
  61429. let encoder;
  61430. if ( renderContextData.currentPass ) {
  61431. renderContextData.currentPass.end();
  61432. encoder = renderContextData.encoder;
  61433. } else {
  61434. _commandEncoderDescriptor.label = 'copyFramebufferToTexture_' + texture.id;
  61435. encoder = this.device.createCommandEncoder( _commandEncoderDescriptor );
  61436. _commandEncoderDescriptor.reset();
  61437. }
  61438. _texelCopyTextureInfoSrc.texture = sourceGPU;
  61439. _texelCopyTextureInfoSrc.origin.x = rectangle.x;
  61440. _texelCopyTextureInfoSrc.origin.y = rectangle.y;
  61441. _texelCopyTextureInfoDst.texture = destinationGPU;
  61442. _extent3D.width = rectangle.z;
  61443. _extent3D.height = rectangle.w;
  61444. encoder.copyTextureToTexture(
  61445. _texelCopyTextureInfoSrc,
  61446. _texelCopyTextureInfoDst,
  61447. _extent3D
  61448. );
  61449. _texelCopyTextureInfoSrc.reset();
  61450. _texelCopyTextureInfoDst.reset();
  61451. _extent3D.reset();
  61452. // mipmaps must be genereated with the same encoder otherwise the copied texture data
  61453. // might be out-of-sync, see #31768
  61454. if ( texture.generateMipmaps ) {
  61455. this.textureUtils.generateMipmaps( texture, encoder );
  61456. }
  61457. if ( renderContextData.currentPass ) {
  61458. const { descriptor } = renderContextData;
  61459. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  61460. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  61461. }
  61462. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  61463. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  61464. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  61465. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  61466. if ( renderContext.viewport ) {
  61467. this.updateViewport( renderContext );
  61468. }
  61469. if ( renderContext.scissor ) {
  61470. this.updateScissor( renderContext );
  61471. }
  61472. } else {
  61473. submit( this.device, encoder.finish() );
  61474. }
  61475. }
  61476. /**
  61477. * Checks if the given compatibility is supported by the backend.
  61478. *
  61479. * @param {string} name - The compatibility name.
  61480. * @return {boolean} Whether the compatibility is supported or not.
  61481. */
  61482. hasCompatibility( name ) {
  61483. if ( this._compatibility[ name ] !== undefined ) {
  61484. return this._compatibility[ name ];
  61485. }
  61486. return super.hasCompatibility( name );
  61487. }
  61488. dispose() {
  61489. this.bindingUtils.dispose();
  61490. this.textureUtils.dispose();
  61491. if ( this.occludedResolveCache ) {
  61492. for ( const buffer of this.occludedResolveCache.values() ) {
  61493. buffer.destroy();
  61494. }
  61495. this.occludedResolveCache.clear();
  61496. }
  61497. if ( this.timestampQueryPool ) {
  61498. for ( const queryPool of Object.values( this.timestampQueryPool ) ) {
  61499. if ( queryPool !== null ) queryPool.dispose();
  61500. }
  61501. }
  61502. if ( this.parameters.device === undefined && this.device !== null ) {
  61503. this.device.destroy();
  61504. }
  61505. }
  61506. }
  61507. /**
  61508. * A IES version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  61509. *
  61510. * @augments SpotLight
  61511. */
  61512. class IESSpotLight extends SpotLight {
  61513. /**
  61514. * Constructs a new IES spot light.
  61515. *
  61516. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  61517. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  61518. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  61519. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  61520. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  61521. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  61522. */
  61523. constructor( color, intensity, distance, angle, penumbra, decay ) {
  61524. super( color, intensity, distance, angle, penumbra, decay );
  61525. /**
  61526. * The IES map. It's a lookup table that stores normalized attenuation factors
  61527. * (0.0 to 1.0) that represent the light's intensity at a specific angle.
  61528. *
  61529. * @type {?Texture}
  61530. * @default null
  61531. */
  61532. this.iesMap = null;
  61533. }
  61534. copy( source, recursive ) {
  61535. super.copy( source, recursive );
  61536. this.iesMap = source.iesMap;
  61537. return this;
  61538. }
  61539. }
  61540. /**
  61541. * A projector light version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  61542. *
  61543. * @augments SpotLight
  61544. */
  61545. class ProjectorLight extends SpotLight {
  61546. /**
  61547. * Constructs a new projector light.
  61548. *
  61549. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  61550. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  61551. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  61552. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  61553. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  61554. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  61555. */
  61556. constructor( color, intensity, distance, angle, penumbra, decay ) {
  61557. super( color, intensity, distance, angle, penumbra, decay );
  61558. /**
  61559. * Aspect ratio of the light. Set to `null` to use the texture aspect ratio.
  61560. *
  61561. * @type {?number}
  61562. * @default null
  61563. */
  61564. this.aspect = null;
  61565. }
  61566. copy( source, recursive ) {
  61567. super.copy( source, recursive );
  61568. this.aspect = source.aspect;
  61569. return this;
  61570. }
  61571. }
  61572. /**
  61573. * This version of a node library represents the standard version
  61574. * used in {@link WebGPURenderer}. It maps lights, tone mapping
  61575. * techniques and materials to node-based implementations.
  61576. *
  61577. * @augments NodeLibrary
  61578. */
  61579. class StandardNodeLibrary extends NodeLibrary {
  61580. /**
  61581. * Constructs a new standard node library.
  61582. */
  61583. constructor() {
  61584. super();
  61585. this.addMaterial( MeshPhongNodeMaterial, 'MeshPhongMaterial' );
  61586. this.addMaterial( MeshStandardNodeMaterial, 'MeshStandardMaterial' );
  61587. this.addMaterial( MeshPhysicalNodeMaterial, 'MeshPhysicalMaterial' );
  61588. this.addMaterial( MeshToonNodeMaterial, 'MeshToonMaterial' );
  61589. this.addMaterial( MeshBasicNodeMaterial, 'MeshBasicMaterial' );
  61590. this.addMaterial( MeshLambertNodeMaterial, 'MeshLambertMaterial' );
  61591. this.addMaterial( MeshNormalNodeMaterial, 'MeshNormalMaterial' );
  61592. this.addMaterial( MeshMatcapNodeMaterial, 'MeshMatcapMaterial' );
  61593. this.addMaterial( LineBasicNodeMaterial, 'LineBasicMaterial' );
  61594. this.addMaterial( LineDashedNodeMaterial, 'LineDashedMaterial' );
  61595. this.addMaterial( PointsNodeMaterial, 'PointsMaterial' );
  61596. this.addMaterial( SpriteNodeMaterial, 'SpriteMaterial' );
  61597. this.addMaterial( ShadowNodeMaterial, 'ShadowMaterial' );
  61598. this.addLight( PointLightNode, PointLight );
  61599. this.addLight( DirectionalLightNode, DirectionalLight );
  61600. this.addLight( RectAreaLightNode, RectAreaLight );
  61601. this.addLight( SpotLightNode, SpotLight );
  61602. this.addLight( AmbientLightNode, AmbientLight );
  61603. this.addLight( HemisphereLightNode, HemisphereLight );
  61604. this.addLight( LightProbeNode, LightProbe );
  61605. this.addLight( IESSpotLightNode, IESSpotLight );
  61606. this.addLight( ProjectorLightNode, ProjectorLight );
  61607. this.addToneMapping( linearToneMapping, LinearToneMapping );
  61608. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  61609. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  61610. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  61611. this.addToneMapping( agxToneMapping, AgXToneMapping );
  61612. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  61613. }
  61614. }
  61615. /*
  61616. const debugHandler = {
  61617. get: function ( target, name ) {
  61618. // Add |update
  61619. if ( /^(create|destroy)/.test( name ) ) log( 'WebGPUBackend.' + name );
  61620. return target[ name ];
  61621. }
  61622. };
  61623. */
  61624. /**
  61625. * This renderer is the new alternative of `WebGLRenderer`. `WebGPURenderer` has the ability
  61626. * to target different backends. By default, the renderer tries to use a WebGPU backend if the
  61627. * browser supports WebGPU. If not, `WebGPURenderer` falls backs to a WebGL 2 backend.
  61628. *
  61629. * @augments Renderer
  61630. */
  61631. class WebGPURenderer extends Renderer {
  61632. /**
  61633. * WebGPURenderer options.
  61634. *
  61635. * @typedef {Object} WebGPURenderer~Options
  61636. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  61637. * @property {boolean} [reversedDepthBuffer=false] - Whether reversed depth buffer is enabled or not.
  61638. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  61639. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  61640. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  61641. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  61642. * @property {number} [samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0 to overwrite the default.
  61643. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  61644. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  61645. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  61646. * @property {number} [outputBufferType=HalfFloatType] - Defines the type of output buffers. The default `HalfFloatType` is recommend for best
  61647. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  61648. */
  61649. /**
  61650. * Constructs a new WebGPU renderer.
  61651. *
  61652. * @param {WebGPURenderer~Options} [parameters] - The configuration parameter.
  61653. */
  61654. constructor( parameters = {} ) {
  61655. let BackendClass;
  61656. if ( parameters.forceWebGL ) {
  61657. BackendClass = WebGLBackend;
  61658. } else {
  61659. BackendClass = WebGPUBackend;
  61660. parameters.getFallback = () => {
  61661. warn( 'WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  61662. return new WebGLBackend( parameters );
  61663. };
  61664. }
  61665. const backend = new BackendClass( parameters );
  61666. //super( new Proxy( backend, debugHandler ) );
  61667. super( backend, parameters );
  61668. /**
  61669. * The generic default value is overwritten with the
  61670. * standard node library for type mapping.
  61671. *
  61672. * @type {StandardNodeLibrary}
  61673. */
  61674. this.library = new StandardNodeLibrary();
  61675. /**
  61676. * This flag can be used for type testing.
  61677. *
  61678. * @type {boolean}
  61679. * @readonly
  61680. * @default true
  61681. */
  61682. this.isWebGPURenderer = true;
  61683. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  61684. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  61685. }
  61686. }
  61687. }
  61688. /**
  61689. * A specialized group which enables applications access to the
  61690. * Render Bundle API of WebGPU. The group with all its descendant nodes
  61691. * are considered as one render bundle and processed as such by
  61692. * the renderer.
  61693. *
  61694. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  61695. * With a WebGL backend, the group can technically be rendered but without
  61696. * any performance improvements.
  61697. *
  61698. * @augments Group
  61699. */
  61700. class BundleGroup extends Group {
  61701. /**
  61702. * Constructs a new bundle group.
  61703. */
  61704. constructor() {
  61705. super();
  61706. /**
  61707. * This flag can be used for type testing.
  61708. *
  61709. * @type {boolean}
  61710. * @readonly
  61711. * @default true
  61712. */
  61713. this.isBundleGroup = true;
  61714. /**
  61715. * This property is only relevant for detecting types
  61716. * during serialization/deserialization. It should always
  61717. * match the class name.
  61718. *
  61719. * @type {string}
  61720. * @readonly
  61721. * @default 'BundleGroup'
  61722. */
  61723. this.type = 'BundleGroup';
  61724. /**
  61725. * Whether the bundle is static or not. When set to `true`, the structure
  61726. * is assumed to be static and does not change. E.g. no new objects are
  61727. * added to the group.
  61728. *
  61729. * If a change is required, an update can still be forced by setting the
  61730. * `needsUpdate` flag to `true`.
  61731. *
  61732. * @type {boolean}
  61733. * @default true
  61734. */
  61735. this.static = true;
  61736. /**
  61737. * The bundle group's version.
  61738. *
  61739. * @type {number}
  61740. * @readonly
  61741. * @default 0
  61742. */
  61743. this.version = 0;
  61744. }
  61745. /**
  61746. * Set this property to `true` when the bundle group has changed.
  61747. *
  61748. * @type {boolean}
  61749. * @default false
  61750. * @param {boolean} value
  61751. */
  61752. set needsUpdate( value ) {
  61753. if ( value === true ) this.version ++;
  61754. }
  61755. }
  61756. /**
  61757. * This module is responsible to manage the rendering pipeline setups in apps.
  61758. * You usually create a single instance of this class and use it to define
  61759. * the output of your render pipeline and post processing effect chain.
  61760. * ```js
  61761. * const renderPipeline = new RenderPipeline( renderer );
  61762. *
  61763. * const scenePass = pass( scene, camera );
  61764. *
  61765. * renderPipeline.outputNode = scenePass;
  61766. * ```
  61767. *
  61768. * Note: This module can only be used with `WebGPURenderer`.
  61769. */
  61770. class RenderPipeline {
  61771. /**
  61772. * Constructs a new render pipeline management module.
  61773. *
  61774. * @param {Renderer} renderer - A reference to the renderer.
  61775. * @param {Node<vec4>} outputNode - An optional output node.
  61776. */
  61777. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  61778. /**
  61779. * A reference to the renderer.
  61780. *
  61781. * @type {Renderer}
  61782. */
  61783. this.renderer = renderer;
  61784. /**
  61785. * A node which defines the final output of the rendering
  61786. * pipeline. This is usually the last node in a chain
  61787. * of effect nodes.
  61788. *
  61789. * @type {Node<vec4>}
  61790. */
  61791. this.outputNode = outputNode;
  61792. /**
  61793. * Whether the default output tone mapping and color
  61794. * space transformation should be enabled or not.
  61795. *
  61796. * This is enabled by default but it must be disabled for
  61797. * effects that expect to be executed after tone mapping and color
  61798. * space conversion. A typical example is FXAA which
  61799. * requires sRGB input.
  61800. *
  61801. * When set to `false`, the app must control the output
  61802. * transformation with `RenderOutputNode`.
  61803. *
  61804. * ```js
  61805. * const outputPass = renderOutput( scenePass );
  61806. * ```
  61807. *
  61808. * @type {boolean}
  61809. */
  61810. this.outputColorTransform = true;
  61811. /**
  61812. * Must be set to `true` when the output node changes.
  61813. *
  61814. * @type {Node<vec4>}
  61815. */
  61816. this.needsUpdate = true;
  61817. const material = new NodeMaterial();
  61818. material.name = 'RenderPipeline';
  61819. /**
  61820. * The full screen quad that is used to render
  61821. * the effects.
  61822. *
  61823. * @private
  61824. * @type {QuadMesh}
  61825. */
  61826. this._quadMesh = new QuadMesh( material );
  61827. this._quadMesh.name = 'Render Pipeline';
  61828. /**
  61829. * The context of the render pipeline stack.
  61830. *
  61831. * @private
  61832. * @type {?Object}
  61833. * @default null
  61834. */
  61835. this._context = null;
  61836. /**
  61837. * The current tone mapping.
  61838. *
  61839. * @private
  61840. * @type {ToneMapping}
  61841. */
  61842. this._toneMapping = renderer.toneMapping;
  61843. /**
  61844. * The current output color space.
  61845. *
  61846. * @private
  61847. * @type {ColorSpace}
  61848. */
  61849. this._outputColorSpace = renderer.outputColorSpace;
  61850. }
  61851. /**
  61852. * When `RenderPipeline` is used to apply rendering pipeline and post processing effects,
  61853. * the application must use this version of `render()` inside
  61854. * its animation loop (not the one from the renderer).
  61855. */
  61856. render() {
  61857. const renderer = this.renderer;
  61858. this._update();
  61859. if ( this._context.onBeforeRenderPipeline !== null ) this._context.onBeforeRenderPipeline();
  61860. const toneMapping = renderer.toneMapping;
  61861. const outputColorSpace = renderer.outputColorSpace;
  61862. renderer.toneMapping = NoToneMapping;
  61863. renderer.outputColorSpace = ColorManagement.workingColorSpace;
  61864. //
  61865. const currentXR = renderer.xr.enabled;
  61866. renderer.xr.enabled = false;
  61867. this._quadMesh.render( renderer );
  61868. renderer.xr.enabled = currentXR;
  61869. //
  61870. renderer.toneMapping = toneMapping;
  61871. renderer.outputColorSpace = outputColorSpace;
  61872. if ( this._context.onAfterRenderPipeline !== null ) this._context.onAfterRenderPipeline();
  61873. }
  61874. /**
  61875. * Returns the current context of the render pipeline stack.
  61876. *
  61877. * @readonly
  61878. * @type {?Object}
  61879. */
  61880. get context() {
  61881. return this._context;
  61882. }
  61883. /**
  61884. * Frees internal resources.
  61885. */
  61886. dispose() {
  61887. this._quadMesh.material.dispose();
  61888. }
  61889. /**
  61890. * Updates the state of the module.
  61891. *
  61892. * @private
  61893. */
  61894. _update() {
  61895. if ( this._toneMapping !== this.renderer.toneMapping ) {
  61896. this._toneMapping = this.renderer.toneMapping;
  61897. this.needsUpdate = true;
  61898. }
  61899. if ( this._outputColorSpace !== this.renderer.outputColorSpace ) {
  61900. this._outputColorSpace = this.renderer.outputColorSpace;
  61901. this.needsUpdate = true;
  61902. }
  61903. if ( this.needsUpdate === true ) {
  61904. const toneMapping = this._toneMapping;
  61905. const outputColorSpace = this._outputColorSpace;
  61906. const context = {
  61907. renderPipeline: this,
  61908. onBeforeRenderPipeline: null,
  61909. onAfterRenderPipeline: null
  61910. };
  61911. let outputNode = this.outputNode;
  61912. if ( this.outputColorTransform === true ) {
  61913. outputNode = outputNode.context( context );
  61914. outputNode = renderOutput( outputNode, toneMapping, outputColorSpace );
  61915. } else {
  61916. context.toneMapping = toneMapping;
  61917. context.outputColorSpace = outputColorSpace;
  61918. outputNode = outputNode.context( context );
  61919. }
  61920. this._context = context;
  61921. this._quadMesh.material.fragmentNode = outputNode;
  61922. this._quadMesh.material.needsUpdate = true;
  61923. this.needsUpdate = false;
  61924. }
  61925. }
  61926. /**
  61927. * When `RenderPipeline` is used to apply rendering pipeline and post processing effects,
  61928. * the application must use this version of `renderAsync()` inside
  61929. * its animation loop (not the one from the renderer).
  61930. *
  61931. * @async
  61932. * @deprecated
  61933. * @return {Promise} A Promise that resolves when the render has been finished.
  61934. */
  61935. async renderAsync() {
  61936. warnOnce( 'RenderPipeline: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  61937. await this.renderer.init();
  61938. this.render();
  61939. }
  61940. }
  61941. /**
  61942. * @deprecated since r183. Use {@link RenderPipeline} instead. PostProcessing has been renamed to RenderPipeline.
  61943. *
  61944. * This class is a wrapper for backward compatibility and will be removed in a future version.
  61945. */
  61946. class PostProcessing extends RenderPipeline {
  61947. /**
  61948. * Constructs a new post processing management module.
  61949. *
  61950. * @param {Renderer} renderer - A reference to the renderer.
  61951. * @param {Node<vec4>} outputNode - An optional output node.
  61952. * @deprecated since r183. Use {@link RenderPipeline} instead.
  61953. */
  61954. constructor( renderer, outputNode ) {
  61955. warnOnce( 'PostProcessing: "PostProcessing" has been renamed to "RenderPipeline". Please update your code to use "THREE.RenderPipeline" instead.' ); // @deprecated, r183
  61956. super( renderer, outputNode );
  61957. }
  61958. }
  61959. /**
  61960. * A readback buffer is used to transfer data from the GPU to the CPU.
  61961. * It is primarily used to read back compute shader results.
  61962. *
  61963. * @augments EventDispatcher
  61964. */
  61965. class ReadbackBuffer extends EventDispatcher {
  61966. /**
  61967. * Constructs a new readback buffer.
  61968. *
  61969. * @param {number} maxByteLength - The maximum size of the buffer to be read back.
  61970. */
  61971. constructor( maxByteLength ) {
  61972. super();
  61973. /**
  61974. * Name used for debugging purposes.
  61975. *
  61976. * @type {string}
  61977. */
  61978. this.name = '';
  61979. /**
  61980. * The mapped, read back array buffer.
  61981. *
  61982. * @type {ArrayBuffer|null}
  61983. */
  61984. this.buffer = null;
  61985. /**
  61986. * The maximum size of the buffer to be read back.
  61987. *
  61988. * @type {number}
  61989. */
  61990. this.maxByteLength = maxByteLength;
  61991. /**
  61992. * This flag can be used for type testing.
  61993. *
  61994. * @type {boolean}
  61995. * @readonly
  61996. * @default true
  61997. */
  61998. this.isReadbackBuffer = true;
  61999. this._mapped = false;
  62000. }
  62001. /**
  62002. * Releases the mapped buffer data so the GPU buffer can be
  62003. * used by the GPU again.
  62004. *
  62005. * Note: Any `ArrayBuffer` data associated with this readback buffer
  62006. * are removed and no longer accessible after calling this method.
  62007. */
  62008. release() {
  62009. this.dispatchEvent( { type: 'release' } );
  62010. }
  62011. /**
  62012. * Frees internal resources.
  62013. */
  62014. dispose() {
  62015. this.dispatchEvent( { type: 'dispose' } );
  62016. }
  62017. }
  62018. /**
  62019. * This special type of texture is intended for compute shaders.
  62020. * It can be used to compute the data of a texture with a compute shader.
  62021. *
  62022. * Note: This type of texture can only be used with `WebGPURenderer`
  62023. * and a WebGPU backend.
  62024. *
  62025. * @augments Texture
  62026. */
  62027. class StorageTexture extends Texture {
  62028. /**
  62029. * Constructs a new storage texture.
  62030. *
  62031. * @param {number} [width=1] - The storage texture's width.
  62032. * @param {number} [height=1] - The storage texture's height.
  62033. */
  62034. constructor( width = 1, height = 1 ) {
  62035. super();
  62036. /**
  62037. * The image object which just represents the texture's dimension.
  62038. *
  62039. * @type {{width: number, height: number}}
  62040. */
  62041. this.image = { width, height };
  62042. /**
  62043. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  62044. *
  62045. * @type {number}
  62046. */
  62047. this.magFilter = LinearFilter;
  62048. /**
  62049. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  62050. *
  62051. * @type {number}
  62052. */
  62053. this.minFilter = LinearFilter;
  62054. /**
  62055. * This flag can be used for type testing.
  62056. *
  62057. * @type {boolean}
  62058. * @readonly
  62059. * @default true
  62060. */
  62061. this.isStorageTexture = true;
  62062. /**
  62063. * When `true`, mipmaps will be auto-generated after compute writes.
  62064. * When `false`, mipmaps must be written manually via compute shaders.
  62065. *
  62066. * @type {boolean}
  62067. * @default true
  62068. */
  62069. this.mipmapsAutoUpdate = true;
  62070. }
  62071. /**
  62072. * Sets the size of the storage texture.
  62073. *
  62074. * @param {number} width - The new width of the storage texture.
  62075. * @param {number} height - The new height of the storage texture.
  62076. */
  62077. setSize( width, height ) {
  62078. if ( this.image.width !== width || this.image.height !== height ) {
  62079. this.image.width = width;
  62080. this.image.height = height;
  62081. this.dispose();
  62082. }
  62083. }
  62084. }
  62085. /**
  62086. * This special type of texture is intended for compute shaders.
  62087. * It can be used to compute the data of a texture with a compute shader.
  62088. *
  62089. * Note: This type of texture can only be used with `WebGPURenderer`
  62090. * and a WebGPU backend.
  62091. *
  62092. * @augments Texture
  62093. */
  62094. class Storage3DTexture extends Texture {
  62095. /**
  62096. * Constructs a new storage texture.
  62097. *
  62098. * @param {number} [width=1] - The storage texture's width.
  62099. * @param {number} [height=1] - The storage texture's height.
  62100. * @param {number} [depth=1] - The storage texture's depth.
  62101. */
  62102. constructor( width = 1, height = 1, depth = 1 ) {
  62103. super();
  62104. //inherited from texture. Must be false for 3DTexture
  62105. this.isArrayTexture = false;
  62106. /**
  62107. * The image object which just represents the texture's dimension.
  62108. *
  62109. * @type {{width: number, height: number, depth: number}}
  62110. */
  62111. this.image = { width, height, depth };
  62112. /**
  62113. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  62114. *
  62115. * @type {number}
  62116. */
  62117. this.magFilter = LinearFilter;
  62118. /**
  62119. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  62120. *
  62121. * @type {number}
  62122. */
  62123. this.minFilter = LinearFilter;
  62124. /**
  62125. * This defines how the texture is wrapped in the depth direction and corresponds to
  62126. * *W* in UVW mapping.
  62127. *
  62128. * @type {number}
  62129. */
  62130. this.wrapR = ClampToEdgeWrapping;
  62131. /**
  62132. * This flag can be used for type testing.
  62133. *
  62134. * @type {boolean}
  62135. * @readonly
  62136. * @default true
  62137. */
  62138. this.isStorageTexture = true;
  62139. /**
  62140. * Indicates whether this texture is a 3D texture.
  62141. *
  62142. * @type {boolean}
  62143. *
  62144. */
  62145. this.is3DTexture = true;
  62146. }
  62147. /**
  62148. * Sets the size of the storage 3d texture.
  62149. *
  62150. * @param {number} width - The new width of the storage texture.
  62151. * @param {number} height - The new height of the storage texture.
  62152. * @param {number} depth - The new depth of the storage texture.
  62153. */
  62154. setSize( width, height, depth ) {
  62155. if ( this.image.width !== width || this.image.height !== height || this.image.depth !== depth ) {
  62156. this.image.width = width;
  62157. this.image.height = height;
  62158. this.image.depth = depth;
  62159. this.dispose();
  62160. }
  62161. }
  62162. }
  62163. /**
  62164. * This special type of texture is intended for compute shaders.
  62165. * It can be used to compute the data of a texture with a compute shader.
  62166. *
  62167. * Note: This type of texture can only be used with `WebGPURenderer`
  62168. * and a WebGPU backend.
  62169. *
  62170. * @augments Texture
  62171. */
  62172. class StorageArrayTexture extends Texture {
  62173. /**
  62174. * Constructs a new storage texture.
  62175. *
  62176. * @param {number} [width=1] - The storage texture's width.
  62177. * @param {number} [height=1] - The storage texture's height.
  62178. * @param {number} [depth=1] - The storage texture's depth.
  62179. */
  62180. constructor( width = 1, height = 1, depth = 1 ) {
  62181. super();
  62182. //inherited from texture
  62183. this.isArrayTexture = true;
  62184. /**
  62185. * The image object which just represents the texture's dimension.
  62186. *
  62187. * @type {{width: number, height: number, depth: number}}
  62188. */
  62189. this.image = { width, height, depth };
  62190. /**
  62191. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  62192. *
  62193. * @type {number}
  62194. */
  62195. this.magFilter = LinearFilter;
  62196. /**
  62197. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  62198. *
  62199. * @type {number}
  62200. */
  62201. this.minFilter = LinearFilter;
  62202. /**
  62203. * This flag can be used for type testing.
  62204. *
  62205. * @type {boolean}
  62206. * @readonly
  62207. * @default true
  62208. */
  62209. this.isStorageTexture = true;
  62210. }
  62211. /**
  62212. * Sets the size of the storage array texture.
  62213. *
  62214. * @param {number} width - The new width of the storage texture.
  62215. * @param {number} height - The new height of the storage texture.
  62216. * @param {number} depth - The new depth of the storage texture.
  62217. */
  62218. setSize( width, height, depth ) {
  62219. if ( this.image.width !== width || this.image.height !== height || this.image.depth !== depth ) {
  62220. this.image.width = width;
  62221. this.image.height = height;
  62222. this.image.depth = depth;
  62223. this.dispose();
  62224. }
  62225. }
  62226. }
  62227. /**
  62228. * This special type of buffer attribute is intended for compute shaders.
  62229. * It can be used to encode draw parameters for indirect draw calls.
  62230. *
  62231. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  62232. * and a WebGPU backend.
  62233. *
  62234. * @augments StorageBufferAttribute
  62235. */
  62236. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  62237. /**
  62238. * Constructs a new storage buffer attribute.
  62239. *
  62240. * @param {number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  62241. * The subsequent parameter is then obsolete.
  62242. * @param {number} itemSize - The item size.
  62243. */
  62244. constructor( count, itemSize ) {
  62245. super( count, itemSize, Uint32Array );
  62246. /**
  62247. * This flag can be used for type testing.
  62248. *
  62249. * @type {boolean}
  62250. * @readonly
  62251. * @default true
  62252. */
  62253. this.isIndirectStorageBufferAttribute = true;
  62254. }
  62255. }
  62256. /**
  62257. * A loader for loading node objects in the three.js JSON Object/Scene format.
  62258. *
  62259. * @augments Loader
  62260. */
  62261. class NodeLoader extends Loader {
  62262. /**
  62263. * Constructs a new node loader.
  62264. *
  62265. * @param {LoadingManager} [manager] - A reference to a loading manager.
  62266. */
  62267. constructor( manager ) {
  62268. super( manager );
  62269. /**
  62270. * Represents a dictionary of textures.
  62271. *
  62272. * @type {Object<string,Texture>}
  62273. */
  62274. this.textures = {};
  62275. /**
  62276. * Represents a dictionary of node types.
  62277. *
  62278. * @type {Object<string,Node.constructor>}
  62279. */
  62280. this.nodes = {};
  62281. }
  62282. /**
  62283. * Loads the node definitions from the given URL.
  62284. *
  62285. * @param {string} url - The path/URL of the file to be loaded.
  62286. * @param {Function} onLoad - Will be called when load completes.
  62287. * @param {Function} onProgress - Will be called while load progresses.
  62288. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  62289. */
  62290. load( url, onLoad, onProgress, onError ) {
  62291. const loader = new FileLoader( this.manager );
  62292. loader.setPath( this.path );
  62293. loader.setRequestHeader( this.requestHeader );
  62294. loader.setWithCredentials( this.withCredentials );
  62295. loader.load( url, ( text ) => {
  62296. try {
  62297. onLoad( this.parse( JSON.parse( text ) ) );
  62298. } catch ( e ) {
  62299. if ( onError ) {
  62300. onError( e );
  62301. } else {
  62302. error( e );
  62303. }
  62304. this.manager.itemError( url );
  62305. }
  62306. }, onProgress, onError );
  62307. }
  62308. /**
  62309. * Parse the node dependencies for the loaded node.
  62310. *
  62311. * @param {Array<Object>} [json] - The JSON definition
  62312. * @return {Object<string,Node>} A dictionary with node dependencies.
  62313. */
  62314. parseNodes( json ) {
  62315. const nodes = {};
  62316. if ( json !== undefined ) {
  62317. for ( const nodeJSON of json ) {
  62318. const { uuid, type } = nodeJSON;
  62319. nodes[ uuid ] = this.createNodeFromType( type );
  62320. nodes[ uuid ].uuid = uuid;
  62321. }
  62322. const meta = { nodes, textures: this.textures };
  62323. for ( const nodeJSON of json ) {
  62324. nodeJSON.meta = meta;
  62325. const node = nodes[ nodeJSON.uuid ];
  62326. node.deserialize( nodeJSON );
  62327. delete nodeJSON.meta;
  62328. }
  62329. }
  62330. return nodes;
  62331. }
  62332. /**
  62333. * Parses the node from the given JSON.
  62334. *
  62335. * @param {Object} json - The JSON definition
  62336. * @param {string} json.type - The node type.
  62337. * @param {string} json.uuid - The node UUID.
  62338. * @param {Array<Object>} [json.nodes] - The node dependencies.
  62339. * @param {Object} [json.meta] - The meta data.
  62340. * @return {Node} The parsed node.
  62341. */
  62342. parse( json ) {
  62343. const node = this.createNodeFromType( json.type );
  62344. node.uuid = json.uuid;
  62345. const nodes = this.parseNodes( json.nodes );
  62346. const meta = { nodes, textures: this.textures };
  62347. json.meta = meta;
  62348. node.deserialize( json );
  62349. delete json.meta;
  62350. return node;
  62351. }
  62352. /**
  62353. * Defines the dictionary of textures.
  62354. *
  62355. * @param {Object<string,Texture>} value - The texture library defines as `<uuid,texture>`.
  62356. * @return {NodeLoader} A reference to this loader.
  62357. */
  62358. setTextures( value ) {
  62359. this.textures = value;
  62360. return this;
  62361. }
  62362. /**
  62363. * Defines the dictionary of node types.
  62364. *
  62365. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  62366. * @return {NodeLoader} A reference to this loader.
  62367. */
  62368. setNodes( value ) {
  62369. this.nodes = value;
  62370. return this;
  62371. }
  62372. /**
  62373. * Creates a node object from the given type.
  62374. *
  62375. * @param {string} type - The node type.
  62376. * @return {Node} The created node instance.
  62377. */
  62378. createNodeFromType( type ) {
  62379. if ( this.nodes[ type ] === undefined ) {
  62380. error( 'NodeLoader: Node type not found:', type );
  62381. return float();
  62382. }
  62383. return new this.nodes[ type ]();
  62384. }
  62385. }
  62386. /**
  62387. * A special type of material loader for loading node materials.
  62388. *
  62389. * @augments MaterialLoader
  62390. */
  62391. class NodeMaterialLoader extends MaterialLoader {
  62392. /**
  62393. * Constructs a new node material loader.
  62394. *
  62395. * @param {LoadingManager} [manager] - A reference to a loading manager.
  62396. */
  62397. constructor( manager ) {
  62398. super( manager );
  62399. /**
  62400. * Represents a dictionary of node types.
  62401. *
  62402. * @type {Object<string,Node.constructor>}
  62403. */
  62404. this.nodes = {};
  62405. /**
  62406. * Represents a dictionary of node material types.
  62407. *
  62408. * @type {Object<string,NodeMaterial.constructor>}
  62409. */
  62410. this.nodeMaterials = {};
  62411. }
  62412. /**
  62413. * Parses the node material from the given JSON.
  62414. *
  62415. * @param {Object} json - The JSON definition
  62416. * @return {NodeMaterial}. The parsed material.
  62417. */
  62418. parse( json ) {
  62419. const material = super.parse( json );
  62420. const nodes = this.nodes;
  62421. const inputNodes = json.inputNodes;
  62422. for ( const property in inputNodes ) {
  62423. const uuid = inputNodes[ property ];
  62424. material[ property ] = nodes[ uuid ];
  62425. }
  62426. return material;
  62427. }
  62428. /**
  62429. * Defines the dictionary of node types.
  62430. *
  62431. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  62432. * @return {NodeLoader} A reference to this loader.
  62433. */
  62434. setNodes( value ) {
  62435. this.nodes = value;
  62436. return this;
  62437. }
  62438. /**
  62439. * Defines the dictionary of node material types.
  62440. *
  62441. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  62442. * @return {NodeLoader} A reference to this loader.
  62443. */
  62444. setNodeMaterials( value ) {
  62445. this.nodeMaterials = value;
  62446. return this;
  62447. }
  62448. /**
  62449. * Creates a node material from the given type.
  62450. *
  62451. * @param {string} type - The node material type.
  62452. * @return {Node} The created node material instance.
  62453. */
  62454. createMaterialFromType( type ) {
  62455. const materialClass = this.nodeMaterials[ type ];
  62456. if ( materialClass !== undefined ) {
  62457. return new materialClass();
  62458. }
  62459. return super.createMaterialFromType( type );
  62460. }
  62461. }
  62462. /**
  62463. * A special type of object loader for loading 3D objects using
  62464. * node materials.
  62465. *
  62466. * @augments ObjectLoader
  62467. */
  62468. class NodeObjectLoader extends ObjectLoader {
  62469. /**
  62470. * Constructs a new node object loader.
  62471. *
  62472. * @param {LoadingManager} [manager] - A reference to a loading manager.
  62473. */
  62474. constructor( manager ) {
  62475. super( manager );
  62476. /**
  62477. * Represents a dictionary of node types.
  62478. *
  62479. * @type {Object<string,Node.constructor>}
  62480. */
  62481. this.nodes = {};
  62482. /**
  62483. * Represents a dictionary of node material types.
  62484. *
  62485. * @type {Object<string,NodeMaterial.constructor>}
  62486. */
  62487. this.nodeMaterials = {};
  62488. /**
  62489. * A reference to hold the `nodes` JSON property.
  62490. *
  62491. * @private
  62492. * @type {?Object[]}
  62493. */
  62494. this._nodesJSON = null;
  62495. }
  62496. /**
  62497. * Defines the dictionary of node types.
  62498. *
  62499. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  62500. * @return {NodeObjectLoader} A reference to this loader.
  62501. */
  62502. setNodes( value ) {
  62503. this.nodes = value;
  62504. return this;
  62505. }
  62506. /**
  62507. * Defines the dictionary of node material types.
  62508. *
  62509. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  62510. * @return {NodeObjectLoader} A reference to this loader.
  62511. */
  62512. setNodeMaterials( value ) {
  62513. this.nodeMaterials = value;
  62514. return this;
  62515. }
  62516. /**
  62517. * Parses the node objects from the given JSON.
  62518. *
  62519. * @param {Object} json - The JSON definition
  62520. * @param {Function} onLoad - The onLoad callback function.
  62521. * @return {Object3D}. The parsed 3D object.
  62522. */
  62523. parse( json, onLoad ) {
  62524. this._nodesJSON = json.nodes;
  62525. const data = super.parse( json, onLoad );
  62526. this._nodesJSON = null; // dispose
  62527. return data;
  62528. }
  62529. /**
  62530. * Async version of {@link NodeObjectLoader#parse}.
  62531. *
  62532. * @param {Object} json - The JSON definition
  62533. * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
  62534. */
  62535. async parseAsync( json ) {
  62536. this._nodesJSON = json.nodes;
  62537. const data = await super.parseAsync( json );
  62538. this._nodesJSON = null; // dispose
  62539. return data;
  62540. }
  62541. /**
  62542. * Parses the node objects from the given JSON and textures.
  62543. *
  62544. * @param {Object[]} json - The JSON definition
  62545. * @param {Object<string,Texture>} textures - The texture library.
  62546. * @return {Object<string,Node>}. The parsed nodes.
  62547. */
  62548. parseNodes( json, textures ) {
  62549. if ( json !== undefined ) {
  62550. const loader = new NodeLoader();
  62551. loader.setNodes( this.nodes );
  62552. loader.setTextures( textures );
  62553. return loader.parseNodes( json );
  62554. }
  62555. return {};
  62556. }
  62557. /**
  62558. * Parses the node objects from the given JSON and textures.
  62559. *
  62560. * @param {Object} json - The JSON definition
  62561. * @param {Object<string,Texture>} textures - The texture library.
  62562. * @return {Object<string,NodeMaterial>}. The parsed materials.
  62563. */
  62564. parseMaterials( json, textures ) {
  62565. const materials = {};
  62566. if ( json !== undefined ) {
  62567. const nodes = this.parseNodes( this._nodesJSON, textures );
  62568. const loader = new NodeMaterialLoader();
  62569. loader.setTextures( textures );
  62570. loader.setNodes( nodes );
  62571. loader.setNodeMaterials( this.nodeMaterials );
  62572. for ( let i = 0, l = json.length; i < l; i ++ ) {
  62573. const data = json[ i ];
  62574. materials[ data.uuid ] = loader.parse( data );
  62575. }
  62576. }
  62577. return materials;
  62578. }
  62579. }
  62580. /**
  62581. * This version of a node library represents a basic version
  62582. * just focusing on lights and tone mapping techniques.
  62583. *
  62584. * @private
  62585. * @augments NodeLibrary
  62586. */
  62587. class BasicNodeLibrary extends NodeLibrary {
  62588. /**
  62589. * Constructs a new basic node library.
  62590. */
  62591. constructor() {
  62592. super();
  62593. this.addLight( PointLightNode, PointLight );
  62594. this.addLight( DirectionalLightNode, DirectionalLight );
  62595. this.addLight( RectAreaLightNode, RectAreaLight );
  62596. this.addLight( SpotLightNode, SpotLight );
  62597. this.addLight( AmbientLightNode, AmbientLight );
  62598. this.addLight( HemisphereLightNode, HemisphereLight );
  62599. this.addLight( LightProbeNode, LightProbe );
  62600. this.addLight( IESSpotLightNode, IESSpotLight );
  62601. this.addLight( ProjectorLightNode, ProjectorLight );
  62602. this.addToneMapping( linearToneMapping, LinearToneMapping );
  62603. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  62604. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  62605. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  62606. this.addToneMapping( agxToneMapping, AgXToneMapping );
  62607. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  62608. }
  62609. }
  62610. /**
  62611. * In earlier three.js versions, clipping was defined globally
  62612. * on the renderer or on material level. This special version of
  62613. * `THREE.Group` allows to encode the clipping state into the scene
  62614. * graph. Meaning if you create an instance of this group, all
  62615. * descendant 3D objects will be affected by the respective clipping
  62616. * planes.
  62617. *
  62618. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  62619. *
  62620. * @augments Group
  62621. */
  62622. class ClippingGroup extends Group {
  62623. /**
  62624. * Constructs a new clipping group.
  62625. */
  62626. constructor() {
  62627. super();
  62628. /**
  62629. * This flag can be used for type testing.
  62630. *
  62631. * @type {boolean}
  62632. * @readonly
  62633. * @default true
  62634. */
  62635. this.isClippingGroup = true;
  62636. /**
  62637. * An array with clipping planes.
  62638. *
  62639. * @type {Array<Plane>}
  62640. */
  62641. this.clippingPlanes = [];
  62642. /**
  62643. * Whether clipping should be enabled or not.
  62644. *
  62645. * @type {boolean}
  62646. * @default true
  62647. */
  62648. this.enabled = true;
  62649. /**
  62650. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  62651. *
  62652. * @type {boolean}
  62653. * @default false
  62654. */
  62655. this.clipIntersection = false;
  62656. /**
  62657. * Whether shadows should be clipped or not.
  62658. *
  62659. * @type {boolean}
  62660. * @default false
  62661. */
  62662. this.clipShadows = false;
  62663. }
  62664. }
  62665. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayCamera, ArrayElementNode, ArrayNode, AssignNode, AtomicFunctionNode, AttributeNode, BackSide, Backend, BarrierNode, BasicEnvironmentNode, BasicLightMapNode, BasicNodeLibrary, BasicShadowMap, BitcastNode, BitcountNode, BlendMode, BoxGeometry, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BuiltinNode, BumpMapNode, BundleGroup, BypassNode, ByteType, CanvasTarget, CineonToneMapping, ClampToEdgeWrapping, ClippingGroup, ClippingNode, CodeNode, Color, ColorManagement, ColorSpaceNode, Compatibility, ComputeBuiltinNode, ComputeNode, ConditionalNode, ConstNode, ContextNode, ConvertNode, CubeCamera, CubeDepthTexture, CubeMapNode, CubeReflectionMapping, CubeRefractionMapping, CubeRenderTarget, CubeTexture, CubeTextureNode, CubeUVReflectionMapping, CullFaceBack, CullFaceFront, CullFaceNone, CustomBlending, CylinderGeometry, DataArrayTexture, DataTexture, DebugNode, DecrementStencilOp, DecrementWrapStencilOp, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightNode, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicDrawUsage, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, EventDispatcher, EventNode, ExpressionNode, FileLoader, FlipNode, Float16BufferAttribute, Float32BufferAttribute, FloatType, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FrustumArray, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLSLNodeBuilder, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, Group, HalfFloatType, HemisphereLight, HemisphereLightNode, IESSpotLight, IESSpotLightNode, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, InputNode, InspectorBase, InspectorNode, InstancedBufferAttribute, InstancedInterleavedBuffer, IntType, InterleavedBuffer, InterleavedBufferAttribute, InvertStencilOp, IrradianceNode, IsolateNode, 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, LinearTransfer, Loader, LoopNode, MRTNode, Material, MaterialBlending, MaterialLoader, MaterialNode, MaterialReferenceNode, MathNode, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, MemberNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoNormalPacking, NoToneMapping, Node, NodeAccess, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeError, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalBlending, NormalGAPacking, NormalMapNode, NormalRGPacking, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OperatorNode, OrthographicCamera, OutputStructNode, OverrideContextNode, PCFShadowMap, PCFSoftShadowMap, PMREMGenerator, PMREMNode, PackFloatNode, ParameterNode, PassNode, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PlaneGeometry, PointLight, PointLightNode, PointShadowNode, PointUVNode, PointsMaterial, PointsNodeMaterial, PostProcessing, ProjectorLight, ProjectorLightNode, PropertyNode, QuadMesh, Quaternion, R11_EAC_Format, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RG11_EAC_Format, 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_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RTTNode, RangeNode, ReadbackBuffer, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceBaseNode, ReferenceNode, ReflectorNode, ReinhardToneMapping, RenderOutputNode, RenderPipeline, RenderTarget, Renderer, RendererReferenceNode, RendererUtils, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RotateNode, SIGNED_R11_EAC_Format, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SIGNED_RG11_EAC_Format, SRGBColorSpace, SRGBTransfer, SampleNode, Scene, ScreenNode, SetNode, ShadowBaseNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, ShortType, Sphere, SphereGeometry, SplitNode, SpotLight, SpotLightNode, SpriteMaterial, SpriteNodeMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StackTrace, StandardNodeLibrary, StaticDrawUsage, Storage3DTexture, StorageArrayElementNode, StorageArrayTexture, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTexture3DNode, StorageTextureNode, StructNode, StructTypeNode, SubBuildNode, SubgroupFunctionNode, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, TimestampQuery, ToneMappingNode, ToonOutlinePassNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnpackFloatNode, UnsignedByteType, UnsignedInt101111Type, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VelocityNode, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WGSLNodeBuilder, WebGLBackend, WebGLCapabilities, WebGLCoordinateSystem, WebGPUBackend, WebGPUCoordinateSystem, WebGPURenderer, WebXRController, WorkgroupInfoNode, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, error, log$1 as log, shaderStages, vectorComponents, warn, warnOnce };
粤ICP备19079148号